Java Graphics How to - Draw on image and scale image








Question

We would like to know how to draw on image and scale image.

Answer

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

public class Main {

  public static void main(String[] args) throws Exception {
    BufferedImage bi = new BufferedImage(100, 100,
        BufferedImage.TYPE_USHORT_GRAY);
    Graphics2D g2d = bi.createGraphics();
    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, 100, 100);
    g2d.setColor( new Color(255, 123, 0));

    g2d.drawLine(100, 100, 1, 1);

    g2d.dispose();
    BufferedImage scaledImage = new BufferedImage(1000, 1000,
        BufferedImage.TYPE_USHORT_GRAY);

    Graphics2D graphics2D = scaledImage.createGraphics();
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(bi, 0, 0, 1000, 1000, null);
    graphics2D.dispose();
    ImageIO.write(scaledImage, "png", new File("c:/Java_Dev/Test.png"));
    bi.flush();
  }
}