java MultipartFile 转ImageInfo
时间: 2023-10-12 09:20:04 浏览: 68
可以使用 Java 的 BufferedImage 类来将 MultipartFile 转换为 ImageInfo。下面是一个简单的示例代码:
```java
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ImageUtils {
public static ImageInfo convertMultipartFileToImageInfo(MultipartFile file) throws IOException {
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
byte[] bytes = file.getBytes();
String contentType = file.getContentType();
return new ImageInfo(bytes, contentType, width, height);
}
}
```
其中,`ImageInfo` 是一个自定义的类,表示图片信息,包括图片数据、类型和尺寸等。你可以根据自己的需要进行修改。
注意:在使用 `ImageIO.read()` 方法时,需要捕获 `IOException` 异常。同时,如果上传的文件不是图片,`bufferedImage` 可能会为 `null`,所以需要在转换之前先判断文件是否为图片类型。