Use the method Image.getScaledInstance
as it show in the example below
import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class ImageTest {
private static final int WIDTH_INCREMENT = 100;
public static void main(String[] args) throws Exception {
BufferedImage image = ImageIO.read(new File("D:\\DDownloads\\Download.png"));
int targetWidth = image.getWidth() + WIDTH_INCREMENT;
// compute height using the aspect ratio
int targetHeight = (int) ((double) targetWidth * image.getHeight()) / image.getWidth();
Image target = image.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH);
// also you can use -1 as new height
// image.getScaledInstance(targetWidth, -1, Image.SCALE_SMOOTH);
// in this case the method computes the correct width by himself
BufferedImage toWrite = new BufferedImage(
targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = toWrite.createGraphics();
g2.drawImage(target, 0, 0, targetWidth, targetHeight, null);
g2.dispose();
ImageIO.write(toWrite, "png", new File("D:\\\\DDownloads\\\\converted.png"));
// next code is to show the both original and converted image on the screen
// Use invokeLater ofr correct initialization of Swing components
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frm = new JFrame("Images");
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.add(new JLabel(new ImageIcon(image)), BorderLayout.NORTH);
frm.add(new JLabel(new ImageIcon(target)), BorderLayout.SOUTH);
frm.pack();
frm.setLocationRelativeTo(null); // center the window
frm.setVisible(true);
}
});
}
}