作者:丘杨(如需转载请注明出处)
背景:
网页中图片和视频资源较多且文件较大,导致网页加载非常慢。图片和视频均存储于minio中,前端会直接访问minio链接
故尝试后端通过压缩图片,前端只展示压缩后的图片来优化加载速度过慢的问题。
其中遇到的一大难题是png动图经过压缩后失去了动图效果。
失败案例总结:
优化图片文件过大导致网页加载慢问题中对于压缩png动图失败案例总结http://t.csdnimg.cn/HC5Gd
成功案例:
maven:
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-imaging</artifactId>
<version>23.9</version>
<classifier>jdk16</classifier>
</dependency>
代码:
import com.aspose.imaging.ColorPaletteHelper;
import com.aspose.imaging.Image;
import com.aspose.imaging.RasterImage;
import com.aspose.imaging.fileformats.png.PngColorType;
import com.aspose.imaging.imageoptions.ApngOptions;
public void addCompression(String fileName) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStream inputStream = readService.getFileInputStream(bucketName, fileName);
String compressName = "compress_" + fileName;
try (Image image = Image.load(inputStream)) {
ApngOptions options = new ApngOptions();
options.setCompressionLevel(9);
options.setProgressive(true);
options.setColorType(PngColorType.IndexedColor);
options.setPalette(ColorPaletteHelper.getCloseImagePalette((RasterImage) image, 1 << 8));
image.save(byteArrayOutputStream, options);
byte[] imgBytes = byteArrayOutputStream.toByteArray();
writeService.upload(imgBytes, compressName);
} catch (Exception e) {
throw e;
}
}
结果:
png文件由1.6mb压缩至389.3kb,并且保留动画效果