BufferedImage 转MultipartFile
时间: 2023-10-13 19:25:56 浏览: 215
JAVA实现多页PDF转一张长图图片
可以使用以下代码将 `BufferedImage` 转换为 `MultipartFile`:
```java
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class ImageUtil {
public static MultipartFile bufferedImageToMultipartFile(BufferedImage image, String fileName) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return new MockMultipartFile(fileName, is, "image/jpeg", fileName.getBytes());
}
}
```
使用示例:
```java
BufferedImage image = ImageIO.read(new File("test.jpg"));
MultipartFile multipartFile = ImageUtil.bufferedImageToMultipartFile(image, "test.jpg");
```
阅读全文