Java Code Snippets: HowTo resize an ImageIcon

See a code snippet showing howto resize a ImageIcon in Java without touching the original file of the image.

Hi there,

perhaps you ran into following problem too:
I had an image in the fileSystem, that i want to use in a JLabel, but it was way to big to match the offered space for the JLabel. One way to solve this is to resize the image itself. But on some reaseons if that is not possible, you have to do it within your code:

ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
		Image image = imageIcon.getImage(); // transform it 
	    Image newimg = image.getScaledInstance(120, 120,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
	    imageIcon = new ImageIcon(newimg);  // transform it back

We used a smooth way to scale the image to get a nice looking new Image. Besides there are some other scaling algorithms offerd by java.awt.Image e.g. SCALE_FAST

Happy Coding

Ähnliche Artikel: