无法使用JPEG压缩来使用ImageIO

时间:2014-08-21 08:37:17

标签: java bufferedimage javax.imageio

我写了一个测试,看看setCompressionQuality()如何影响文件的大小和质量。但是,创建的所有文件都是相同的大小,表明我可能做错了。我已经在线查看了很多关于如何执行此操作的指南以及有关stackoverflow的其他问题,我仍然无法发现我的错误。有任何想法吗。下面的SSCCE。

背景:为什么我使用JPEG作为截图!!是的我知道PNG是工作的工具,但我正在尝试在低带宽链路上运行的自定义内部远程桌面解决方案中实现“低质量”模式,质量真的无关紧要用户可以看看发生了什么。

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

public class ImageCompressionJpg {
    public static void main(String[] args) throws AWTException, IOException {
        Robot robot = new Robot();

        BufferedImage image = robot.createScreenCapture(new Rectangle(Toolkit
                .getDefaultToolkit().getScreenSize()));

        ImageIO.write(image, "jpg", new File("screen.standard.jpg"));

        // JPEGs, different qualities 0 - 1
        for (float quality = 0; quality <= 1; quality += 0.2) {
            ImageWriter writer = (ImageWriter) ImageIO
                    .getImageWritersByFormatName("jpeg").next();
            ImageWriteParam param = writer.getDefaultWriteParam();

            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality);
            ImageOutputStream ios = ImageIO.createImageOutputStream(new File(
                    String.format("screen.%.1f.jpg", quality)));
            writer.setOutput(ios);

            writer.write(image);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您必须使用不同的write()重载并将IIOImage和您的自定义参数传递给它:

ImageWriter writer  = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam param = writer.getDefaultWriteParam();

param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);

writer.setOutput(new FileImageOutputStream(
    new File(String.format("screen.%.1f.jpg", quality))));
writer.write(null, new IIOImage(image, null, null), param);
writer.dispose();

答案 1 :(得分:1)

将ImageParams传递给ImageWriter

writer.write(null, new IIOImage(image, null, null), param);