//压缩图片400KB以下
int kb = 400 * 1024;
long fileSize = file.getSize();
if (fileSize > 100 * 1024) {
int smallSize = (int) (fileSize % kb == 0 ? fileSize / kb : fileSize / kb + 1);
double size = Math.ceil(Math.sqrt(smallSize));
log.info(String.valueOf(size));
Image image = ImageIO.read(file.getInputStream());
int width = image.getWidth(null);
int height = image.getHeight(null);
//log.info(width+"x"+height);
int widthSmall = (int) (width / size);
int heightSmall = (int) (height / size);
//log.info(widthSmall+"x"+heightSmall);
BufferedImage buffi = new BufferedImage(widthSmall, heightSmall, BufferedImage.TYPE_INT_RGB);
Graphics g = buffi.getGraphics();
g.drawImage(image, 0, 0, widthSmall, heightSmall, null);
g.dispose();
//文件的名称
String filename = file.getOriginalFilename().split("\\.")[0];
//文件的格式
String type = file.getOriginalFilename().split("\\.")[1];
//将newImage写入字节数组输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(buffi,type,baos);
//将文件储存到本地
//ImageIO.write(buffi, "jpg", new File("H:\\work\\yz\\img\\"+filename+ (new Random().nextInt(10000) + 1)+"."+type));
file = new MockMultipartFile(file.getOriginalFilename(), baos.toByteArray());
}
- THE END -
最后修改:2023年7月10日
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://www.95app.top/springboot%e4%b8%8a%e4%bc%a0%e5%9b%be%e7%89%87%e5%b9%b6%e5%8e%8b%e7%bc%a9/