前后端分离项目将前端传递的MultipartFile 文件的大小进行压缩,在转换回MultipartFile
时间: 2023-11-12 19:59:00 浏览: 41
可以使用Java的ImageIO类对图片进行压缩,然后再将压缩后的图片转换为MultipartFile。具体实现可以参考以下代码:
```java
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ImageUtils {
public static MultipartFile compress(MultipartFile file, int maxWidth, int maxHeight, float quality) throws IOException {
BufferedImage image = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
int width = image.getWidth();
int height = image.getHeight();
if (width <= maxWidth && height <= maxHeight) {
return file;
}
float scale = Math.min((float) maxWidth / width, (float) maxHeight / height);
int newWidth = (int) (width * scale);
int newHeight = (int) (height * scale);
BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = newImage.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(image, 0, 0, newWidth, newHeight, null);
graphics.dispose();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(newImage, "jpg", outputStream);
byte[] bytes = outputStream.toByteArray();
outputStream.close();
return new CompressedMultipartFile(bytes, file.getOriginalFilename(), file.getContentType());
}
private static class CompressedMultipartFile implements MultipartFile {
private final byte[] bytes;
private final String name;
private final String contentType;
public CompressedMultipartFile(byte[] bytes, String name, String contentType) {
this.bytes = bytes;
this.name = name;
this.contentType = contentType;
}
@Override
public String getName() {
return name;
}
@Override
public String getOriginalFilename() {
return name;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public boolean isEmpty() {
return bytes == null || bytes.length == 0;
}
@Override
public long getSize() {
return bytes.length;
}
@Override
public byte[] getBytes() {
return bytes;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(bytes);
}
@Override
public void transferTo(File file) throws IOException, IllegalStateException {
throw new UnsupportedOperationException();
}
}
}
```
其中,maxWidth和maxHeight是压缩后的图片最大宽度和高度,quality是压缩质量,取值范围为0到1。