BufferedImage直接转MultipartFile
时间: 2023-10-12 07:16:09 浏览: 89
由于java.awt.image.BufferedImage和org.springframework.web.multipart.MultipartFile是不同的类,不能直接转换。但是可以通过以下步骤将BufferedImage转换为MultipartFile:
1. 通过ImageIO将BufferedImage转换为字节数组ByteArrayOutputStream
2. 创建一个MultipartFile对应的实现类CommonsMultipartFile对象
3. 将字节数组和文件名设置到CommonsMultipartFile对象中
以下是示例代码:
```
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ImageUtils {
public static MultipartFile convertToMultipartFile(BufferedImage image, String filename) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "png", outputStream);
CommonsMultipartFile multipartFile = new CommonsMultipartFile();
multipartFile.setBytes(outputStream.toByteArray());
multipartFile.setOriginalFilename(filename);
multipartFile.setContentType("image/png");
return multipartFile;
}
}
```
使用方法:
```
BufferedImage image = ...;
MultipartFile multipartFile = ImageUtils.convertToMultipartFile(image, "image.png");
```
阅读全文