Вопрос

I want to compress a jpeg image, that is, decrease its resolution, without resizing it in any way. Is there any good Java library that will help me doing it? There are lots of similar posts in SO, but most of them end up resizing the image as well.

If not, how can I do it programatically? Say, for an argument of 0.9, the image's resolution will decrease by a factor of 0.1...

Это было полезно?

Решение

Typically "resolution" means size. Do you mean the JPEG quality instead? That is the only way I can think of to compress it without resizing it.

If so, you can use the Java2D ImageIO API. Something like the following would work (adapted from this page):

BufferedImage bufferedImage = ImageIO.read(...);

ImageWriter writer = (ImageWriter)ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(...);

File file = new File(...);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(bufferedImage, null, null);
writer.write(null, image, iwp);
writer.dispose();

Unfortunately, I don't think there's a way to get the existing JPEG quality of an image, so you'll have to use some fixed value for the compression quality.

Другие советы

You can do this by using Java2D API and set the compression quality for the output image, which will reduce the image quality and file size but will maintain the same width and height of the original image

    File imageFile = new File("original.jpg");
    File compressedImageFile = new File("compressed.jpg");

    InputStream is = new FileInputStream(imageFile);
    OutputStream os = new FileOutputStream(compressedImageFile);

    float quality = 0.7f; // Change this as needed

    BufferedImage image = ImageIO.read(is);

    // get all image writers for JPG format
    Iterator<ImageWriter> writers = ImageIO
            .getImageWritersByFormatName("jpg");

    if (!writers.hasNext())
        throw new IllegalStateException("No writers found");

    ImageWriter writer = (ImageWriter) writers.next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);

    // set compression quality
    ImageWriteParam param = writer.getDefaultWriteParam();

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

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

    // clean resources e.g. close streams

If you want something more advanced, check imageJ and [Fiji][2] they are very powerful image processing libraries in Java with easy to use APIs.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top