Java Graphics How to - Scale a BufferedImage(Image)








Question

We would like to know how to scale a BufferedImage(Image).

Answer

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//from w  w w .  ja va  2 s .co  m
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Main {
  public static void main(String[] args) throws IOException {

    final int SCALE = 2;

    Image img = new ImageIcon(new URL("http://www.java2s.com/style/download.png")).getImage();

    BufferedImage bi = new BufferedImage(SCALE * img.getWidth(null), SCALE
        * img.getHeight(null), BufferedImage.TYPE_INT_ARGB);

    Graphics2D grph = (Graphics2D) bi.getGraphics();
    grph.scale(SCALE, SCALE);

    grph.drawImage(img, 0, 0, null);
    grph.dispose();

    ImageIO.write(bi, "png", new File("double_size.png"));
  }
}