Java Graphics How to - Resize image java with getScaledInstance








Question

We would like to know how to resize image java with getScaledInstance.

Answer

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
// w ww  .  j  a v a  2 s  . c o  m
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Main {
  public static void main(String[] args) throws Exception {
    ImageIcon ii = new ImageIcon("C:/Java_Dev/test.jpg");
    BufferedImage bi = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = (Graphics2D) bi.createGraphics();
    g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,
        RenderingHints.VALUE_RENDER_QUALITY));
    boolean b = g2d.drawImage(ii.getImage(), 0, 0, 50, 50, null);
    System.out.println(b);
    ImageIO.write(bi, "jpg", new File("C:/Java_Dev/test.jpg"));
  }
}