How to Resize an Image Using Java

Resizing image in Java

If you have an java.awt.Image, resizing it doesn't require any additional libraries. Just do:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

Obviously, replace newWidth and newHeight with the dimensions of the specified image.

Notice the last parameter: it tells the runtime the algorithm you want to use for resizing.

There are algorithms that produce a very precise result, however these take a large time to complete.

You can use any of the following algorithms:

  • Image.SCALE_DEFAULT: Use the default image-scaling algorithm.
  • Image.SCALE_FAST: Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.
  • Image.SCALE_SMOOTH: Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.
  • Image.SCALE_AREA_AVERAGING: Use the Area Averaging image scaling algorithm.
  • Image.SCALE_REPLICATE: Use the image scaling algorithm embodied in the ReplicateScaleFilter class.

See the Javadoc for more info.

How can I resize an image using Java?

After loading the image you can try:

BufferedImage createResizedCopy(Image originalImage, 
int scaledWidth, int scaledHeight,
boolean preserveAlpha)
{
System.out.println("resizing...");
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}

how to resize Image in java?

I use affine transformation to achieve this task, here is my code, hope it helps

/**
* scale image
*
* @param sbi image to scale
* @param imageType type of image
* @param dWidth width of destination image
* @param dHeight height of destination image
* @param fWidth x-factor for transformation / scaling
* @param fHeight y-factor for transformation / scaling
* @return scaled image
*/
public static BufferedImage scale(BufferedImage sbi, int imageType, int dWidth, int dHeight, double fWidth, double fHeight) {
BufferedImage dbi = null;
if(sbi != null) {
dbi = new BufferedImage(dWidth, dHeight, imageType);
Graphics2D g = dbi.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight);
g.drawRenderedImage(sbi, at);
}
return dbi;
}

Resize a picture to fit a JLabel

Outline

Here are the steps to follow.

  • Read the picture as a BufferedImage.
  • Resize the BufferedImage to another BufferedImage that's the size of the JLabel.
  • Create an ImageIcon from the resized BufferedImage.

You do not have to set the preferred size of the JLabel. Once you've scaled the image to the size you want, the JLabel will take the size of the ImageIcon.

Read the picture as a BufferedImage

BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
e.printStackTrace();
}

Resize the BufferedImage

Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(),
Image.SCALE_SMOOTH);

Make sure that the label width and height are the same proportions as the original image width and height. In other words, if the picture is 600 x 900 pixels, scale to 100 X 150. Otherwise, your picture will be distorted.

Create an ImageIcon

ImageIcon imageIcon = new ImageIcon(dimg);

Java image resize, maintain aspect ratio

Here we go:

Dimension imgSize = new Dimension(500, 100);
Dimension boundary = new Dimension(200, 200);

Function to return the new size depending on the boundary:

public static Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {

int original_width = imgSize.width;
int original_height = imgSize.height;
int bound_width = boundary.width;
int bound_height = boundary.height;
int new_width = original_width;
int new_height = original_height;

// first check if we need to scale width
if (original_width > bound_width) {
//scale width to fit
new_width = bound_width;
//scale height to maintain aspect ratio
new_height = (new_width * original_height) / original_width;
}

// then check if we need to scale even with the new height
if (new_height > bound_height) {
//scale height to fit instead
new_height = bound_height;
//scale width to maintain aspect ratio
new_width = (new_height * original_width) / original_height;
}

return new Dimension(new_width, new_height);
}

In case anyone also needs the image resizing code, here is a decent solution.

If you're unsure about the above solution, there are different ways to achieve the same result.

Image Resizing in Java to reduce image size

You don't need a full blown Image processing library for simply resizing an image.

The recommended approach is by using progressive bilinear scaling, like so (feel free to use this method as is in your code):

public BufferedImage scale(BufferedImage img, int targetWidth, int targetHeight) {

int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = img;
BufferedImage scratchImage = null;
Graphics2D g2 = null;

int w = img.getWidth();
int h = img.getHeight();

int prevW = w;
int prevH = h;

do {
if (w > targetWidth) {
w /= 2;
w = (w < targetWidth) ? targetWidth : w;
}

if (h > targetHeight) {
h /= 2;
h = (h < targetHeight) ? targetHeight : h;
}

if (scratchImage == null) {
scratchImage = new BufferedImage(w, h, type);
g2 = scratchImage.createGraphics();
}

g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(ret, 0, 0, w, h, 0, 0, prevW, prevH, null);

prevW = w;
prevH = h;
ret = scratchImage;
} while (w != targetWidth || h != targetHeight);

if (g2 != null) {
g2.dispose();
}

if (targetWidth != ret.getWidth() || targetHeight != ret.getHeight()) {
scratchImage = new BufferedImage(targetWidth, targetHeight, type);
g2 = scratchImage.createGraphics();
g2.drawImage(ret, 0, 0, null);
g2.dispose();
ret = scratchImage;
}

return ret;

}

Code modified and cleaned from the original at Filthy Rich Clients.


Based on your comment, you can reduce quality and encode JPEG bytes like so:

image is the BufferedImage.

ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName("jpeg").next();

ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.2f); // Change this, float between 0.0 and 1.0

writer.setOutput(ImageIO.createImageOutputStream(os));
writer.write(null, new IIOImage(image, null, null), param);
writer.dispose();

Now, since os is a ByteArrayOutputStream, you can Base64 encode it.

String base64 = Base64.encode(os.toByteArray());


Related Topics



Leave a reply



Submit