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();}
}

3 comments:

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

    ReplyDelete
  2. Hi there, I found your web site via Google while looking for a related topic, your web site came up, it looks great. I have bookmarked it in my google bookmarks.social media marketing

    ReplyDelete
  3. Hello, i think that i saw you visited my website thus i came to “return the favor”.I am attempting to find things to enhance my site!I suppose its ok to use some of your ideas!! singapore business directory free listing

    ReplyDelete