java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java图片高效压缩

Java图片压缩三种高效压缩方案详细解析

作者:很少更新

图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,这篇文章主要介绍了Java图片压缩三种高效压缩方案的相关资料,需要的朋友可以参考下

一、基于OpenCV的智能尺寸压缩

java public static void extracted2() { '
String path = "C:\test.jpg"; 
String savePath = "D:\compressed.jpg"; 
int maxWidth = 800; 
int maxHeight = 600; 
compressImage(new File(path), new File(savePath), maxWidth, maxHeight); 
}
compressImage 写法为kotlin语法法,需要自己转换
fun compressImage(inputFile: File, outputFile: File, maxWidth: Int, maxHeight: Int) {
        try {
            val image = ImageIO.read(inputFile)
            val originalWidth = image.width
            val originalHeight = image.height
            var newWidth = originalWidth
            var newHeight = originalHeight

            // 计算新的宽度和高度,保持比例
            if (originalWidth > maxWidth || originalHeight > maxHeight) {
                val ratio = Math.min(maxWidth.toDouble() / originalWidth, maxHeight.toDouble() / originalHeight)
                newWidth = (originalWidth * ratio).toInt()
                newHeight = (originalHeight * ratio).toInt()
            }

            val resizedImage = BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB)
            resizedImage.createGraphics().apply {
                drawImage(image.getScaledInstance(newWidth, newHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null)
                dispose()
            }

            // 确保输出目录存在
            val outputPath: Path = Paths.get(outputFile.parent)
            if (!Files.exists(outputPath)) {
                Files.createDirectories(outputPath)
            }

            ImageIO.write(resizedImage, "jpg", outputFile)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

技术亮点:

适用场景:

二、JPEG质量参数压缩

java public static void extracted4() { 
	for (int i = 1; i <=10; i++) { 
		float quality = 0.1f * i; 
		compressImage(inputFile, outputFile, quality); 
	} 
}
public static void compressImage(File inputFile, File outputFile, float quality) throws IOException {
        // 读取图片
        BufferedImage image = ImageIO.read(inputFile);

        // 获取图片写入器
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("webp");
        ImageWriter writer = writers.next();

        // 设置写入器的输出目标
        ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
        writer.setOutput(ios);

        // 创建图片写入器配置
        IIOImage imageIO = new IIOImage(image, null, null);
        ImageWriteParam param = writer.getDefaultWriteParam();

        // 设置压缩质量
        if (param.canWriteCompressed()) {
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality);
        }

        // 写入图片
        writer.write(null, imageIO, param);

        // 关闭资源
        ios.close();
        writer.dispose();
    }

关键技术:

压缩效果对比:

质量参数文件大小清晰度
0.345KB可接受
0.7120KB良好
1.0350KB无损

三、WebP高效格式转换

public static void extracted6() {
        String path = "C:\\Users\\美众\\Pictures\\test2.jpg";
        for (int i = 1; i <=10; i++) {
            float quality = 0.0f + i * 0.1f;
            System.out.println("quality:" + quality);
            String savePath = "D:\\save\\test2-webp-"+quality+".jpg";
            File inputFile = new File(path); // 原始图片文件
            File outputFile = new File(savePath);
            try {
                jpg2webp(inputFile, outputFile,quality);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
public static void jpg2webp(File oldfile, File newfile,float quality){
        try {
            // 获取原始文件的编码
            BufferedImage image = ImageIO.read(oldfile);
            // 创建WebP ImageWriter实例
            ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
            // 配置编码参数
            WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
            // 设置压缩模式
            writeParam.setCompressionMode(WebPWriteParam.MODE_EXPLICIT);
            System.out.println("getCompressionTypes:"+JSON.toJSON(writeParam.getCompressionTypes()));
//            "Lossy"-有损,"Lossless"-无损
            writeParam.setCompressionType(writeParam.getCompressionTypes()[0]);
            writeParam.setCompressionQuality(quality);
            // 配置ImageWriter输出
            writer.setOutput(new FileImageOutputStream(newfile));
            // 进行编码,重新生成新图片
            writer.write(null, new IIOImage(image, null, null), writeParam);
            System.out.println("jpg文件转成webp格式成功");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

核心优势:

性能对比:

格式质量0.8加载速度兼容性
JPEG150KB100%
WebP95KB较快95%+

四、方案选型建议

总结 

到此这篇关于Java图片压缩三种高效压缩方案的文章就介绍到这了,更多相关Java图片高效压缩内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文