两天两夜,1M图片优化到100kb!
Java后端技术
共 6720字,需浏览 14分钟
·
2022-01-15 21:20
往期热门文章:
一、图像压缩
https://www.jiqizhixin.com/graph/technologies/08b2b25e-21a0-48e1-9de8-f91d424adfe1
二、Java数字图像处理
三、图像压缩实战
ImageIO.read()
可以将图像读取到 BufferedImage 对象:File input = new File("ceshi.jpg");
BufferedImage image = ImageIO.read(input);
ImageIO.getImageWritersByFormatName()
可以返回一个Iterator,其中包含了通过命名格式对图像进行编码的 ImageWriter。Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
ImageIO.createImageOutputStream()
可以创建一个图像的输出流对象,有了该对象后就可以通过 ImageWriter.setOutput()
将其设置为输出流。File compressedImageFile = new File("bbcompress.jpg");
OutputStream os =new FileOutputStream(compressedImageFile);
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.01f);
setCompressionQuality()
方法。setCompressionQuality()
方法的参数是一个 0-1 之间的数,0.0 表示尽最大程度压缩,1.0 表示保证图像质量很重要。对于有损压缩方案,压缩质量应该控制文件大小和图像质量之间的权衡(例如,通过在写入 JPEG 图像时选择量化表)。对于无损方案,压缩质量可用于控制文件大小和执行压缩所需的时间之间的权衡(例如,通过优化行过滤器并在写入 PNG 图像时设置 ZLIB 压缩级别)。public class Demo {
public static void main(String[] args) {
try {
File input = new File("ceshi.jpg");
BufferedImage image = ImageIO.read(input);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
File compressedImageFile = new File("bbcompress.jpg");
OutputStream os = new FileOutputStream(compressedImageFile);
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.01f);
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
} catch (IOException e) {
e.printStackTrace();
}
}
}
四、其他开源库
<dependency>
<groupId>org.openpnp</groupId>
<artifactId>opencv</artifactId>
<version>4.5.1-2</version>
</dependency>
OpenCV.loadShared();
Mat src = Imgcodecs.imread(imagePath);
MatOfInt dstImage = new MatOfInt(Imgcodecs.IMWRITE_JPEG_QUALITY, 1);
Imgcodecs.imwrite("resized_image.jpg", sourceImage, dstImage);
opencvCompress压缩完成,所花时间:1070
jdkCompress压缩完成,所花时间:322
四、一点点心声
往期热门文章:
3、Java8 Stream:2万字20个实例,玩转集合的筛选、归约、分组、聚合
评论