Java Resize Image to Fixed Width and Height Example
In this tutorial we show a Java Resize Image to Fixed Width and Height Example. We can resize an image using different algorithms. Each algorithm focuses on a different aspect. You can configure the image scaling process using you own custom algorithm.
Java Resize Image Example
This example is sufficient if you only want to do some small image scaling. You can configure your scaling algorithm by using one of the following configuration.
Image.SCALE_DEFAULT
– uses the default image-scaling algorithm.Image.SCALE_FAST
– uses an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.Image.SCALE_SMOOTH
– uses an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.Image.SCALE_REPLICATE
– use the image scaling algorithm embodied in theReplicateScaleFilter
class.Image.SCALE_AREA_AVERAGING
– uses the area averaging image scaling algorithm.
package com.memorynotfound.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ResizeImageExample {
public static void main(String... args) throws IOException {
File input = new File("/tmp/duke.png");
BufferedImage image = ImageIO.read(input);
BufferedImage resized = resize(image, 500, 500);
File output = new File("/tmp/duke-resized-500x500.png");
ImageIO.write(resized, "png", output);
}
private static BufferedImage resize(BufferedImage img, int height, int width) {
Image tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage resized = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = resized.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return resized;
}
}
The major problem with single step scaling is they don’t generally produce quality output, as they focus on taking the original and squeezing it into a smaller space, usually by dropping out a lot of pixel information. If you are resizing large images please use dedicated libraries for the optimal performance/quality of the image.
Converted Images
To demonstrate the result, we added the following table. The first image is the original. The subsequent are different images that we have resized in various sizes.
duke.png (original) | duke-resized-50x50.jpg | duke-resized-100x100.jpg | duke-resized-500x500.jpg |
---|---|---|---|
Size: 9KB | Size: 2KB | Size: 5KB | Size: 51KB |
References
- ImageIO JavaDoc
- Image JavaDoc
- Image.getScaledInstance() JavaDoc
- BufferedImage JavaDoc
- Graphics2D JavaDoc
This worked well! Thanks…
Thanks very much
its great