How to resize an image in Java ?

I’m not the expert in Java image processing, but a chance given to implement this re-sized feature in user image upload form, which request re-sized the large image to a smaller size with fixed width and height.

Graphics2D is providing the image re-size feature as follows :


BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();		

According to some articles, if you want to increase the re-sized image quality, you can add the RenderingHints as follows :


BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

1. Example

Here is a website snapshot, the following program will re-size this image to a fixed width and height image (100 x 100).

mkyong.jpg (640 x 310) – 46KB

mkyong

2. Source code

ImageTest.java

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

/*
 * @author mkyong
 *
 */
public class ImageTest {

	private static final int IMG_WIDTH = 100;
	private static final int IMG_HEIGHT = 100;
	
	public static void main(String [] args){
		
	try{
			
		BufferedImage originalImage = ImageIO.read(new File("c:\\image\\mkyong.jpg"));
		int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
			
		BufferedImage resizeImageJpg = resizeImage(originalImage, type);
		ImageIO.write(resizeImageJpg, "jpg", new File("c:\\image\\mkyong_jpg.jpg")); 
			
		BufferedImage resizeImagePng = resizeImage(originalImage, type);
		ImageIO.write(resizeImagePng, "png", new File("c:\\image\\mkyong_png.jpg")); 
			
		BufferedImage resizeImageHintJpg = resizeImageWithHint(originalImage, type);
		ImageIO.write(resizeImageHintJpg, "jpg", new File("c:\\image\\mkyong_hint_jpg.jpg")); 
			
		BufferedImage resizeImageHintPng = resizeImageWithHint(originalImage, type);
		ImageIO.write(resizeImageHintPng, "png", new File("c:\\image\\mkyong_hint_png.jpg")); 
				
	}catch(IOException e){
		System.out.println(e.getMessage());
	}
		
    }
	
    private static BufferedImage resizeImage(BufferedImage originalImage, int type){
	BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
	Graphics2D g = resizedImage.createGraphics();
	g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
	g.dispose();
		
	return resizedImage;
    }
	
    private static BufferedImage resizeImageWithHint(BufferedImage originalImage, int type){
		
	BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
	Graphics2D g = resizedImage.createGraphics();
	g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
	g.dispose();	
	g.setComposite(AlphaComposite.Src);

	g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
	RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	g.setRenderingHint(RenderingHints.KEY_RENDERING,
	RenderingHints.VALUE_RENDER_QUALITY);
	g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
	RenderingHints.VALUE_ANTIALIAS_ON);
	
	return resizedImage;
    }	
}

See result :

JPG (4KB) PNG (9KB) JPG + Hints (4KB) PNG + Hints (9KB)
mkyong_jpg mkyong_png mkyong_hint_jpg mkyong_hint_png

Conclusion

As you see the re-sized image , the file size of the re-sized PNG image is larger than the re-sized JPEG image, but the PNG quality is better than JPG after re-sized. The hints will not take any effect in JPG format, however i didn’t see any difference between PNG and PNG + hints either, even someone told about adding the rendering hints will increase the image quality?

P.S Please share Java image tips if you know some :)

References

  1. http://java.sun.com/j2se/1.4.2/docs/api/javax/imageio/ImageIO.html
  2. http://java.sun.com/j2se/1.4.2/docs/api/java/awt/image/BufferedImage.html
  3. http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Graphics2D.html
  4. http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
  5. http://www.servletsuite.com/servlets/imagescale.htm
  6. http://www.componenthouse.com/article-20

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
nayef
Guest
nayef

after drawing and disposing the graphics, rendering hints were set. shouldn’t the rendering hins be set before drawing?

Krzysztof Kamil B?k
Guest
Krzysztof Kamil B?k

Yes, the rendering hints are supposed to be set before the drawing process begins.

Graphics2D graphics = cropped.createGraphics();

graphics.setComposite(AlphaComposite.Src);

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

graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

graphics.drawImage(nonCropped, 0, 0, 128, 128, cropX, cropY, cropX + width, cropY + height, null);

graphics.dispose();

hendra
Guest
hendra

thanks mkyong ! Resizing method using Graphic2D really work for me.

Thiago Marques Silva
Guest
Thiago Marques Silva

Thanks!

Ray Renaldi
Guest
Ray Renaldi

I have never left any post or comments in any of the tutorial I’ve read before. But I would like to thank you as you have provided me with immense help in solving some of my problems. I am like yourself is a coding junky and love sharing knowledge libraries and learning new things as we go. Again thank you for all the tutorials you provided and for the effort you have put in writing every single one of them. Hats off..

Latest Tutorials
Guest
Latest Tutorials

I run your code but its giving me that exception …… Here is the Image link :: https://www.dropbox.com/s/quq17fbpuje5f92/UMG_00602527054308_T11_cvrart.jpg?dl=0

Exception in thread “main” java.lang.IllegalArgumentException: Numbers of source Raster bands and source color space components do not match
at java.awt.image.ColorConvertOp.filter(ColorConvertOp.java:482)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.acceptPixels(JPEGImageReader.java:1263)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(Native Method)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1231)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:1034)
at javax.imageio.ImageIO.read(ImageIO.java:1448)
at javax.imageio.ImageIO.read(ImageIO.java:1308)
at com.rockville.utility.ImageTest.main(ImageTest.java:30)

Antonio Galván
Guest
Antonio Galván

Thank you men. I was making some code to resize a file, but, I have false color in the result. Now I see the solution by your code.

Thank you a lot.

Linush Perera
Guest
Linush Perera

thanks for this great stuff !! owe you a pint !! looking forward for more cheers !!

Zirkan
Guest
Zirkan

If resizeing does not work to add g.finalize(); before g.dispose() to get a resized image.

Hope this helps.

Ameen
Guest
Ameen

Is there an alternative for ImageIO?? For some images if i use “ImageIO.read(new File(“C:imagetest.jpg”));”, it gives me unsupported image format. Please suggest me to use an alternative for ImageIO

Ameen
Guest
Ameen

Any updates???

momy
Guest
momy
??GIF?JPG????????????? ????? public static void reduceImg(String imgsrc, String imgdist, int widthdist, int heightdist) { try { File srcfile = new File(imgsrc); if (!srcfile.exists()) { return; } Image src = javax.imageio.ImageIO.read(srcfile); BufferedImage tag= new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null); /// tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_AREA_AVERAGING), 0, 0, null); FileOutputStream out = new FileOutputStream(imgdist); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(tag); out.close(); } catch (IOException ex) { ex.printStackTrace(); } }
Ivan E.
Guest
Ivan E.

He utilizado el código, pero he cambiado algunas líneas.

public static void reduceImg(String imgsrc, String imgdist,String type, int widthdist,
int heightdist) {
try {
File srcfile = new File(imgsrc);
if (!srcfile.exists()) {
return;
}
Image src = javax.imageio.ImageIO.read(srcfile);

BufferedImage tag= new BufferedImage((int) widthdist, (int) heightdist,
BufferedImage.TYPE_INT_RGB);

tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
// tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_AREA_AVERAGING), 0, 0, null);

FileOutputStream out = new FileOutputStream(imgdist);
ImageIO.write(tag, type, out);
out.close();

} catch (IOException ex) {
ex.printStackTrace();
}
}

Luca
Guest
Luca

Great Ivan! This is the best solutions I’ve found.This line does the trick:

tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

From the doc: Image.SCALE_SMOOTH “Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed”.
Infact the image quality is really better than using the other params!

Fatih
Guest
Fatih

Thanks

Dara
Guest
Dara

That is good. I wrote may programs inclusing image resize to manipulate image. You can check them at http://www.javatheprogram.blogspot.com

Semika
Guest
Semika

Thank you so much.

Pankaj
Guest
Pankaj

Actually using RenderingHints do affect the output image quality and size. I have written a similar program and played with it for sometime to check it out. In your case the image is of website and quality is not too good to recognize the difference from naked eye. Check it out here:

http://www.journaldev.com/615/java-image-resize-program-using-graphics2d-example

Abdul Rehman
Guest
Abdul Rehman
Hi! I have an implementation to resize an image with rendering hints and converting it to TYPE_BYTE_GRAY. Code works fine until i get an original image having type of TYPE_BYTE_BINARY. Let’s say if i do not convert it to TYPE_BYTE_GRAY but only want to resize it. How am i gonna do that? I have tried it against drawImage(img, 0, 0, null) and drawImage(img, 0, 0, newWidth, newHeight, null) but was not successful. In first case the image gets cropped and in second case it throws exception. So what i want to ask is, Is there any way to resize TYPE_BYTE_BINARY… Read more »
Anand Singh
Guest
Anand Singh

its giving exceptin

java.lang.IllegalArgumentException: Can’t load standard profile: sRGB.pf

Bruce Wen
Guest
Bruce Wen
	public static BufferedImage resizeImage(BufferedImage image, int longer, int width,
			int height, boolean isWithHint) {
		int oldWidth = image.getWidth();
		int oldHeight = image.getHeight();

		boolean isWidthLonger = oldWidth > oldHeight;

		int newWidth = -1;
		int newHeight = -1;

		if (longer > 0) {
			if (isWidthLonger) {
				newWidth = longer;
				newHeight = NumberUtil.convert(new double[] { longer
						* ((double) oldHeight / (double) oldWidth) })[0]
						.intValue();
			} else {
				newHeight = longer;
				newWidth = NumberUtil.convert(new double[] { longer
						* ((double) oldWidth / (double) oldHeight) })[0]
						.intValue();
			}
		} else {
			newWidth = width;
			newHeight = height;
		}
		
		int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();

		return isWithHint ? resizeImageWithHint(image, type,
				newWidth, newHeight) : resizeImageWithoutHint(image,
						type, newWidth, newHeight);
	}
trackback
Java resize | Greenlivingand

[…] How to resize an image in Java ?Sep 29, 2009 … I’m not the expert in Java image processing, it’s a chance given to implement this re-sized feature in user image upload form, which request … […]

Arjun
Guest
Arjun

Thanks a ton, was stuck on this topic for days before i found your post.
Keep up the good work..

Arjun

Claudio
Guest
Claudio

grooooooooooosooooooooooooooooooooo me solucionaste la vida chabonnnnn!!!

Jiten K
Guest
Jiten K

Great example!!! thanks Mkyong!!! You are great!!!

JSupport
Guest
JSupport

Check out this

How to Resize Image according to the screen size using Java

How to resize an image in Java

Misgana
Guest
Misgana

Nice short and precise.Thanks a lot.

Nghia Nguyen
Guest
Nghia Nguyen

Great example!!!

Spidey
Guest
Spidey

This made my Icons lose their transparency, any idea why?

Hugo Garcia-Cotte
Guest
Hugo Garcia-Cotte

There is a little error in your code, the rendering hints have to be given before you use the drawImage method on g.
And then you can see the rendering is better.

lolka
Guest
lolka

+1

or this is some trick, but i suppose rendering hits must be set BEFORE drawing an image

Ram
Guest
Ram

Hi Dude,

Very nice Example for Sacling the buffred Image …

Thanks ,

Ram

noha mohamed
Guest
noha mohamed

it is a good work .. :)

Olcay Erta?
Guest
Olcay Erta?

Thank you very much. It was really helpful.

trackback
Resim Boyutlama / Image Resizing

[…] kayna?? olarak; http://www.mkyong.com/java/how-to-resize-an-image-in-java/ Posted in HowTo, Programlama | Tagged image-resize, […]