Change the storage quality of JPEG images in Java

Occasionally you may want to resize and save a JPEG image. If you can use ImageMagick, the story is quick, but if you really want to complete it with Java only, you will use ImageIO.

However, please note that the storage quality of JPEG images is automatically set to "75" with the simplest implementation method (check with Java 8). I was addicted to it.

How to specify storage quality

The implementation itself is simple, but if you want to change the storage quality, it is NG.

    public static byte[] resize(final byte[] src, final double scale) throws IOException {
        try (ByteArrayInputStream is = new ByteArrayInputStream(src);
             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            BufferedImage srcImage = ImageIO.read(is);
            BufferedImage destImage = resizeImage(srcImage, scale);

            //Storage quality will be "75"
            ImageIO.write(destImage, "jpeg", os);
            return os.toByteArray();
        }
    }

How to specify storage quality

This is the correct answer. You can specify the storage quality quality from 0 to 1.0. 1.0 is equivalent to quality 100.

    public static byte[] resize(final byte[] src, final double scale, final float quality) throws IOException {
        try (ByteArrayInputStream is = new ByteArrayInputStream(src);
             ByteArrayOutputStream os = new ByteArrayOutputStream();
             ImageOutputStream ios = ImageIO.createImageOutputStream(os)) {
            BufferedImage srcImage = ImageIO.read(is);
            BufferedImage destImage = resizeImage(srcImage, scale);

            //Storage quality follows user specifications
            ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality);
            writer.setOutput(ios);
            writer.write(null, new IIOImage(destImage, null, null), param);
            writer.dispose();

            return os.toByteArray();
        }
    }

Supplement

The implementation of the resizing method resizeImage that appeared in the previous two examples is as follows. The image quality is not good by default when resizing the image, but you can improve the image quality by specifying TYPE_BICUBIC when converting to affine.

    public static BufferedImage resizeImage(final BufferedImage image, final double scale) throws IOException {
        int width = (int) (image.getWidth() * scale);
        int height = (int) (image.getHeight() * scale);
        BufferedImage resizedImage = new BufferedImage(width, height, image.getType());

        //Resize by affine conversion (priority is given to image quality)
        AffineTransform transform = AffineTransform.getScaleInstance(scale, scale);
        AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);
        op.filter(image, resizedImage);

        return resizedImage;
    }

When resizing in Java, the memory & CPU load becomes unacceptably large as the image data becomes large, so I think that the scenes that can be used are quite limited.

Recommended Posts

Change the storage quality of JPEG images in Java
The story of writing Java in Emacs
The story of low-level string comparison in Java
The story of making ordinary Othello in Java
About the idea of anonymous classes in Java
The story of learning Java in the first programming
Measure the size of a folder in Java
Feel the passage of time even in Java
Import files of the same hierarchy in Java
Get the URL of the HTTP redirect destination in Java
Summarize the additional elements of the Optional class in Java 9
Change java encoding in windows
Implementation of gzip in java
Implementation of tri-tree in Java
Was done in the base year of the Java calendar week
A quick explanation of the five types of static in Java
How to derive the last day of the month in Java
Access the network interface in Java
[Java] Delete the elements of List
Guess the character code in Java
Examine the system information of AWS Lambda operating environment in Java
[Java] Get the dates of the past Monday and Sunday in order
[Java version] The story of serialization
[Swift] Change the textColor of UIDatePicker
Specify the java location in eclipse.ini
Output the difference between each field of two objects in Java
Find out the list of fonts available in AWS Lambda + Java
List of members added in Java 9
The milliseconds to set in /lib/calendars.properties of Java jre is UTC
Parsing the COTOHA API in Java
Examine the list of timezone IDs available in the Java ZoneId class
Get the public URL of a private Flickr file in Java
Consideration of "Java policy change" risk
Let's create a TODO application in Java 5 Switch the display of TODO
List of types added in Java 9
Order of processing in the program
I want to change the value of Attribute in Selenium of Ruby
The origin of Java lambda expressions
Implementation of like function in Java
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
Call the super method in Java
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
The story of acquiring Java Silver in two months from completely inexperienced.
This and that of the implementation of date judgment within the period in Java
How to find the total number of pages when paging in Java
Sample program that returns the hash value of a file in Java
How to change the value of a variable at a breakpoint in intelliJ
[Socket communication (Java)] Impressions of implementing Socket communication in practice for the first time
How to get the absolute path of a directory running in Java
Find the maximum and minimum of the five numbers you entered in Java
[Java] java.lang.NoClassDefFoundError: Addressing the problem of falling in org / jsoup / safety / Whitelist
Change the save destination of the image to S3 in the Rails app. Part 2
Implementation of DBlayer in Java (RDB, MySQL)
Check the contents of the Java certificate store
Java reference to understand in the figure
Examine the memory usage of Java elements
[Java] Get the day of the specific day of the week
OCR in Java (character recognition from images)
Try using the Stream API in Java
Call the Windows Notification API in Java