How to resize an image in Java
To resize an image in Java programming language is simple and easy. It is done within just 2 minutes. We will use the getScaledInstance method in Java to scale the perfectly and automatically.
How to use the getScaledInstance() method in Java?
Well, it creates a scaled version of the image. getScaledInstance() is a method in java.awt.Image and it is parameterized with int width, int height, and hints. Now, let us resize an image in Java and see how it works.
getScaledInstance(width, height, Image.SCALE_SMOOTH);
Walk-through
Simply follow these steps to make a simple java project by creating an auto-scaling image using Java or resize an image in Java. The first step is to create a Java project and right-click on the Source Packages and create a folder and name it as res (we need it later). Next, right-click and create a new Java package for your java class.
Once you have your JFrame, put a jLabel for your image. Make sure your JFrame is set to null layout. If you don’t set your JFrame to null layout, and you set it on default. When you insert an image to a jLabel, and you are on the free design layout, the image will then scale it to its original size. Try to figure it out. Coding it is pretty simple. You will need to declare the Image and ImageIcon class.
Syntax
private void scaleMouseClicked(java.awt.event.MouseEvent evt) { ImageIcon imageicon = new ImageIcon(getClass().getResource("/res/image.jpg")); Image image = (imageicon).getImage().getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_SMOOTH); imageicon = new ImageIcon(image); img.setIcon(imageicon); }
We use ImageIcon class to create an image from a filename. getResource() is where the image file is stored. “res” is the folder where the image is stored. Image class represents the graphical images and get the image from imageicon to scale it. “img” is the variable name of the jLabel. getScaledInstance() method is getting the exact width and height of the jLabel to fit the image in jLabel perfectly. Image.SCALE_SMOOTH gives higher priority to the image smoothness.
Sample Output