开发者

How to save jpeg Image file size after read--rotate-write operations in Java?

Im trying to read a JPEG image as BufferedImage, rotate and save it as another jpeg image from file system. But there is a problem : after these operations I cannot proceed same file size.

Here the code

//read Image
BufferedImage img = ImageIO.read(new File(path));
//rotate Image
BufferedImage rotatedImage = new BufferedImage(image.getHeight(),
            image.getWidth(), BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g2d = (Gra开发者_高级运维phics2D) rotatedImage.getGraphics();
    g2d.rotate(Math.toRadians(PhotoConstants.ROTATE_LEFT));

    int height=-rotatedImage.getHeight(null);
    g2d.drawImage(image, height, 0, null);
    g2d.dispose();

//Write Image
    Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter)iter.next();
    // instantiate an ImageWriteParam object with default compression options
    ImageWriteParam iwp = writer.getDefaultWriteParam();
    try {
        FileImageOutputStream output = null;
        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(0.98f);   // an integer between 0 and 1
        // 1 specifies minimum compression and maximum quality

        File file = new File(path);
        output = new FileImageOutputStream(file);
        writer.setOutput(output);
        IIOImage iioImage = new IIOImage(image, null, null);
        writer.write(null, iioImage, iwp);
        output.flush();
        output.close();
        writer.dispose();

Is it possible to access compressionQuality parameter of original jpeg image in the beginning. when I set 1 to compression quality, the image gets bigger size. Otherwise I set 0.9 or less the image gets smaller size. How can i proceed the image size after these operations?

Thank you,


What do you mean - do you want to read the compression rate of the original file?

Please note that even with the same compression settings, the filesize might vary, due to the JPEG compression algorithm. So a rotated image does not always have the exact same size as the unrotated/original version, even if all options (like compression rate, quality settings etc.) are the same.


If there is really now way to read the compression quality from the metadata, as a last resort, what you could do is use a binary search for the quality. Start with 0.5, if the file is too small try 0.75 and so on (up to 5 tries or so). This is a bit slow of course, but depending on your use case it might be OK.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜