Saturday, July 20, 2013

BufferedImage to Image

Sometimes you might want to convert from BufferedImage object to Image object. This task can be done by using the createImage(ImageProducer producer) method of any component. A class that implements the ImageProducer interface is FilteredImageSource. Its constructor is FilteredImageSource(ImageProducer producer, ImageFilter filter). RGBImageFilter is a class that implements the ImageFilter interface. This class has a method called filterRGB that can be override to filter rgb color of the image.  In the example below, the createImage method is used to create an image object based on the image data source and the image filter. Since, we do not want to change the color of original image, the filterRGB method simply returns rgb value. By returning the rgb value, you can make sure that there is no change from the source to the destination image.

public void BufferedImageToImage(String filename){
ImageFilter filter = new RGBImageFilter() {
  public final int filterRGB(int x, int y, int rgb) {
        return rgb; //nothing change to the image    
    }
  };

try{
  BufferedImage srcimg=ImageIO.read(new File(filename));
      Image img = createImage(new FilteredImageSource(srcimg.getSource(),filter));
      //do something with the image object img

}catch(Exception e){e.printStackTrace();}
}

1 comment:

  1. This is useful for storing image data in memory.
    Thank u!

    ReplyDelete