简体   繁体   English

减少java中图像的大小

[英]Reduce the size of an image in java

I want to make sure that an image in my application is not more than 200x200 px and the image size is not more than 150 kB. 我想确保我的应用程序中的图像不超过200x200像素,图像大小不超过150 kB。 For example, if the file size of image is more than 150 kB i need to make it 150 kB. 例如,如果图像的文件大小超过150 kB,我需要将其设为150 kB。 The image can be of type jpeg,png etc. 图像可以是jpeg,png等类型。

I have the following code for resizing an image to a given width and height 我有以下代码用于将图像调整为给定的宽度和高度

private BufferedImage resize(BufferedImage img, int newW, int newH) {
        int w = img.getWidth();
        int h = img.getHeight();
        BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
        Graphics2D g = dimg.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
        g.dispose();
        return dimg;
    }

But im not sure how to go about reducing the file size to 150 kB. 但我不知道如何将文件大小减小到150 kB。 How to do that in java ?.Some example would be really appreciated. 如何在java中做到这一点?。一些例子将非常感激。

Thank You 谢谢

就像一个选项 - 图像魔术 - 它也有一些Java的便利包装,所以你可以轻松使用它。

Does your question have any practical relevance or is it just theoretical? 您的问题是否具有实际意义,还是仅仅是理论上的?

A 200x200 pixel image with a colour depth of 24 bit will uncompressed require 117kB. 颜色深度为24位的200x200像素图像未压缩需要117kB。 If you use any reasonable JPEG encoder, it will also never exceed 150kB for such an image. 如果您使用任何合理的JPEG编码器,对于这样的图像,它也将永远不会超过150kB。

您只能多次重新调整图像,以低于确定的文件大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM