1. Introduction

In this tutorial, we’re going to learn how to resize (scale) an image using Java. We’ll explore both core Java and open-source third-party libraries that offer the image resize feature.

It’s important to mention that we can scale images both up and down. In the code samples in this tutorial, we’ll resize images to smaller sizes since, in practice, that’s the most common scenario.

2. Resize an Image Using Core Java

Core Java offers the following options for resizing images:

2.1. java.awt.Graphics2D

Graphics2D is the fundamental class for rendering 2-dimensional shapes, text, and images on the Java platform.

Let’s start by resizing an image using Graphics2D:

BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
    BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = resizedImage.createGraphics();
    graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
    return resizedImage;

Let’s see what the image looks like before and after resizing:

The BufferedImage.TYPE_INT_RGB parameter indicates the color model of the image. A full list of available values is available in the official Java BufferedImage documentation.

Graphics2D accepts additional parameters called RenderingHints. We use RenderingHints to influence different image processing aspects and most importantly image quality and processing time.

We can add a RenderingHint using the setRenderingHint method:

graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

A full list of RenderingHints can be found in this Oracle tutorial.

#java #image #web-development #developer

How to Resize (Scale) an Image using Java
2.25 GEEK