Saturday, March 19, 2011

How to write image to a jpeg file ?

This can be done in three steps :

  1. Create a image object (BufferedImage)
  2. Draw something to the image. (Using Graphics2D API)
  3. Write the image object to a jpeg file (Using ImageIO api)

The following sample will create a 200x200 image. Draw a diagonal and a circle on it. Then write the image to the file "macteki.jpg"

* File :
* Author :
* Description :
*   Draw a simple image and write it to a jpeg file (macteki.jpg).
* Tested with : JDK 1.6

import java.awt.image.BufferedImage;

class JpegWriter
  public static void main(String[] args) throws Exception

    // create a 200x200 image
    int width=200, height=200;
    BufferedImage image= new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    // draw something to the image
    java.awt.Graphics graphics=image.getGraphics();

    // create a Graphics2D object for drawing shape
    java.awt.Graphics2D gr=(java.awt.Graphics2D) graphics;
    gr.setStroke(new java.awt.BasicStroke(5));  // set pen width to 5 pixels
    gr.setColor(new java.awt.Color(255,0,0));   // set Color to RED
    gr.drawLine(0,0,width,height);  // draw diagonal
    gr.drawArc(0,0,width,height,0,360); // draw circle

    // write the image to a Jpeg File
    javax.imageio.ImageIO.write(image, "JPEG", new"macteki.jpg"));

No comments:

Post a Comment