Java Code Snippets: HowTo resize an ImageIcon


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:

7 Kommentare

  1. Habe schon lange nach einer Lösung gesucht, bei dir hab ich es direkt verstanden. Keine Ahnung weshalb. Glaube die anderen Lösungen waren zu überladen.
    Ty

  2. Man kann in ein JLabel auch HTML-Code eintragen.
    label.setText(“ „);
    Das Bild d:/picture.png wird nun mit 100 x 30 Pixeln gezeichnet, egal wie gr0ß das Original ist.

  3. HTML-Code wird hier nicht angezeigt. Der JLabel-Text des vorigen Eintrags lautet ohne spitze Klammern:
    HTML src=’file:d:/picture.png‘ width=100 height=30 \HTML

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.

*