Friday, February 13, 2009

Converting Image to BufferedImage in JAVA


While working on some project i was bound in some situation.....
  1. For opening image i have to use java.awt.Image class.
  2. For saving drawn image to jpg i have to use ImageIo class.
  3. So for passing ImageIO.write() method i need image object to bufferedImage object.
It is not only one situation when you need this, Sometime when reading
image java.awt.Image class is very useful for opening images from
particular path.

So their are number of tricks to do so.
I am posting here my favorite way of conversion.
Just go through it.

First i loaded image in Image object via Toolkit class.
Then i created a blank BufferedImage object of same dimension.
Then i just draw Image object into BufferedImage object.
Now your BufferedImage object consist the same image.

For full source code follow the link:-


* Program for Converting Image Object to BufferedImage Object

* Copyright 2009 @ yuvadeveloper

* Code By:- Prashant Chandrakar



import java.awt.*;

import java.awt.image.*;

class Convert


public static void main(String as[])


////opening image in Image Object

Image img = Toolkit.getDefaultToolkit().getImage("test.jpeg");

////taking dimension of image

int width = img.getWidth(null);

int height = img.getHeight(null);

////creating a bufferedImage object of same dimension as image

BufferedImage bimg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

////taking graphics object from BufferedImage

Graphics2D gg = bimg.createGraphics();

////drawing Image objects image into graphics of buffered image object

gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);

///disposing graphics.