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");
    

Last updated: Dec 26, 2023