Skip to content
← Back to blog
·1 min read

How to adapt the size of an image inside JLabel

swingui

When adding an image to a JLabel component in Java you want to have the image resized and not cropped. This simple piece of code will help to get the job done.

ImageIcon image = new ImageIcon("../image.png");
int scale = 3;

int width = image.getIconWidth();
int height = image.getIconHeight();
BufferedImage buffer = new BufferedImage(scale * width, scale * height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = buffer.createGraphics();
graphics.scale(scale,scale);
image.paintIcon(null, graphics, 0, 0);
graphics.dispose();

JLabel label = new JLabel(new ImageIcon(buffer)));

Worked for me, hope it works for you.