3 Ways to Resize Images in Java

image resize java

How Do You Resize Images in Java?

Java is a popular object-oriented programming language originally designed and used for distributed enterprise applications. Today it is widely used for mobile development, as the programming language for Android smartphone applications, and is commonly used for edge devices and internet of things (IoT) development.

Resizing an image means removing pixels and reducing its physical size, or “blowing up” the image by adding pixels, which will reduce image quality. If a resize operation changes the aspect ratio of an image, it will result in “squeezing” the image out of its current proportions.

Java provides several techniques for programmatic bulk image resize, including the getScaledInstance() method and the Graphics2D class. We’ll also show how to use Cloudinary to resize images in Java while automatically adjusting the image to focus on objects of interest.

In this article, we cover the following techniques to resize images in Java:

  1. Resizing an Image Using BufferedImage.getScaledInstance()
  2. Resizing an Image Using Graphics2D
  3. Automatically Resize and Crop Images in Java with Cloudinary

Techniques to Resize Images in Java

Resizing an Image Using BufferedImage.getScaledInstance()

You can resize an image in Java using the getScaledInstance() function, available in the Java Image class. We’ll use the BufferedImage class that extends the basic Image class. It stores images as an array of pixels.

First, we import the necessary Java libraries:

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

 

Now, we create an object from the BufferedImage class, and use the ImageIO.read() function to read an image from the file system. The File() method calls the File class constructor, taking the path of the image as an argument.

BufferedImage bufferedImage = ImageIO.read(new File("C:\\example.png"));

We now have a new object containing the image, which provides the getScaledInstance() method, which we can use to get a resized version of the image. The method takes the following arguments:

  • Target width in pixels after resizing
  • Target height in pixels after resizing
  • Image scaling algorithm (if you don’t have a special preference, you can use Image.SCALE_DEFAULT which uses the default sampling algorithm)

Here is how to scale the source image to 800 x 500 pixels:

Image image = bufferedImage.getScaledInstance(800, 500, Image.SCALE_DEFAULT);

 

Note that this operation scales the bufferedImage object in memory, but does not save the resized image to the file system, and also does not display the image.

Let’s arrange the resized image using a JFrame. We’ll set the layout to FlowLayout, which specifies that components in the JFrame should be displayed from left to right, and set the size of the JFrame to a larger size than the image, ensuring it will be shown in its entirety.

ImageIcon icon = new ImageIcon(image);
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());
frame.setSize(1200, 800);

 

The last step is to display the image to the user. We’ll do this using a JLabel object, adding the JLabel to the frame and setting visibility to true.

JLabel jLabel = new JLabel();
jLabel.setIcon(icon);
frame.add(jLabel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 

Automatically resize and crop image with AI

Resizing an Image Using Graphics2D

Another option for resizing an image in Java is the Graphics2D class. This class extends the Graphics class to provide fine-grained control over geometry, coordinate transformations, and color management of 2-dimensional shapes and images.

Here are the required imports:

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

 

Like in the previous example, we use ImageIo.read() and the File() method to read the image from the file system and store it as a BufferedImage object:

BufferedImage bufferedImage = ImageIO.read(new File("C:\\example.png"));

 

We create another object that will store the resize operation result:

BufferedImage bufferedImageResult = new BufferedImage(
        resizeWidth,
        resizeHeight,
        bufferedImage.getType()
);

 

Now it’s time to use the g2d class. We’ll call the createGraphics() method, passing the bufferedImageResult object. This returns a g2d (Graphics2D) object.

Graphics2D g2d = bufferedImageResult.createGraphics();

 

We can now use the drawImage() function on the g2d object, which takes the following arguments:

  • A BufferedImage object
  • X and Y coordinates. For a resize operation, these should be set to 0.
  • The new height and width after resizing.
  • ImageObserver – handles notifications of image loading; not needed in this case and can be left as null.

The code looks like this:

g2d.drawImage(
        bufferedImage, 
        0, 
        0, 
        resizeWidth, 
        resizeHeight, 
        null
);

 

We use the following command to dispose of context and resources used by g2d, which are not necessary for the next steps:

g2d.dispose();

 

Finally, we save the resized image in the local directory using the ImageIo.write() function.

String formatName = imagePathToWrite.substring(
        imagePathToWrite.lastIndexOf(".") + 1
);
ImageIO.write(
        bufferedImageResult, 
        formatName, 
        new File(imagePathToWrite)
);

 

Automatically Resize and Crop Images in Java with Cloudinary

A cloud-based service for managing images and videos, Cloudinary offers a generous free-forever subscription plan. While on that platform, you can upload your images, and apply built-in effects, filters, and modifications. You can also resize images automatically, focusing on the most important elements with AI, or adapt them to your website design without having to manually crop or scale them.

You can set the target dimensions of your resized image by specifying width, height, and/or the target aspect ratio as qualifiers of your resize transformation.

You can change the dimensions of an uploaded image by setting the image’s height, width, and/or aspect ratio, and Cloudinary automatically resizes or crops the image to fit into the requested size.

For example, this original image is 1200 x 1200 pixels:

three ways to resize

Resizing the image to 200 x 200 pixels, using crop, scale, fill and pad results in the following images:

3 ways to resize 200px

Get started with automated resize and cropping today!

  1. Get a free Cloudinary account
  2. Install the Java SDK
  3. Deliver the crop transformations shown above as follows:
    # focus on the model in portrait crop
    cloudinary.url().transformation(new Transformation().height(200).width(200).crop("crop")).imageTag("https://res.cloudinary.com/demo/image/upload/docs/model.jpg");
    # detect the face for thumbnail crop
    cloudinary.url().transformation(new Transformation().height(200).width(200).crop("crop")).imageTag("https://res.cloudinary.com/demo/image/upload/docs/model.jpg");
    # crop to a banner automatically focusing on region of interest
    cloudinary.url().transformation(new Transformation().aspectRatio("2.5").width(450).crop("crop")).imageTag("https://res.cloudinary.com/demo/image/upload/docs/model.jpg");
    

     

QUICK TIPS
Tamas Piros
Cloudinary Logo Tamas Piros

In my experience, here are tips that can help you better resize images in Java:

  1. Use Image.SCALE_SMOOTH for better quality
    When resizing images with getScaledInstance(), use Image.SCALE_SMOOTH instead of Image.SCALE_DEFAULT to improve the image quality. This algorithm applies a better interpolation method for smoother resizing, particularly when reducing image size.
  2. Leverage AffineTransform for precise transformations
    For more complex resizing operations, use AffineTransform with the Graphics2D class. This allows you to scale images with fine-grained control over rotation, scaling, and translation, preserving quality even during drastic size changes.
  3. Use BufferedImage.TYPE_INT_ARGB for transparency
    When resizing images that include transparency (e.g., PNG images), use BufferedImage.TYPE_INT_ARGB to preserve the alpha channel during the resize operation. This ensures that any transparency in the original image is maintained in the resized version.
  4. Ensure thread-safety when resizing in parallel
    If resizing images in parallel (e.g., in a web application), be cautious about thread safety. Each BufferedImage and Graphics2D operation should be isolated within its own thread to prevent race conditions or unexpected behavior in multithreaded environments.
  5. Apply anti-aliasing for sharper images
    Before drawing images with Graphics2D, enable anti-aliasing with g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);. This improves the quality of the resized image by smoothing out jagged edges, especially on diagonals or curves.
  6. Use drawImage() with RenderingHints for quality control
    Combine drawImage() with RenderingHints to fine-tune how images are scaled. For example, use RenderingHints.KEY_INTERPOLATION with RenderingHints.VALUE_INTERPOLATION_BICUBIC for high-quality image scaling when performance isn’t the top priority.
  7. Resize proportionally to maintain aspect ratio
    Always calculate the resized image dimensions proportionally to maintain the original aspect ratio. For example, if resizing based on width, calculate the height as newHeight = (originalHeight / originalWidth) * newWidth to avoid distortion.
  8. Implement caching for resized images
    If resizing the same images frequently, implement a caching mechanism to store resized versions. This saves time and processing power by preventing repeated resizing operations on the same image.
  9. Utilize Graphics2D double buffering for smoother drawing
    When working with images in a UI, enable double buffering to reduce flickering and improve performance when resizing images dynamically. This can be done with JComponent.setDoubleBuffered(true).
  10. Offload large-scale resizing to Cloudinary
    For applications dealing with large volumes of images, offload resizing tasks to Cloudinary. It automatically handles resizing, cropping, and optimization with its API, and can apply AI-based cropping to focus on the most important part of the image, improving performance and reducing server load.

These advanced techniques will help you optimize image resizing in Java, ensuring better quality, performance, and scalability in your projects.

Last updated: Oct 1, 2024