曹耘豪的博客

Java图片处理

  1. 转为JPG并压缩
  2. 功能背景
  3. 参考

转为JPG并压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@SneakyThrows
public static byte[] convertToJPG(byte[] bytes) {
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream);
ImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);

BufferedImage read = ImageIO.read(imageInputStream);

Iterator<ImageWriter> jpg = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter imageWriter = jpg.next();

ImageWriteParam writeParam = imageWriter.getDefaultWriteParam();
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(0.8f);

imageWriter.setOutput(imageOutputStream);
imageWriter.write(null, new IIOImage(read, null, null), writeParam);

imageOutputStream.close();
imageWriter.dispose();

return outputStream.toByteArray();
}

功能背景

由于第三方接口对图片大小有限制,所以考虑用代码压缩,不过最终没有使用。而是使用阿里云oss自带的压缩,原图上传到oss

对于阿里云oss,只需要在后面增加?x-oss-process=image/format,jpg/quality,Q_80即可

参考

   /