Image to BufferedImage

What is the easiest way to convert a Image to a bufferedImage for writing to a file?

The short answer is to start with a BufferedImage! For instance, use ImageIO.read to read.
The long aswer, well here's the long answer:
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class X {
    //preserves image's colormodel. Assumes image is loaded
    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage)
            return (BufferedImage) image;
        ColorModel cm = getColorModel(image);
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        return copy(createBufferedImage(cm, width, height), image);
    public static BufferedImage toBufferedImage(Image image, int type) {
        if (image instanceof BufferedImage && ((BufferedImage)image).getType() == type)
            return (BufferedImage) image;
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        return copy(new BufferedImage(width, height, type), image);
    //Returns target. Assumes source is loaded
    public static BufferedImage copy(BufferedImage target, Image source) {
        Graphics2D g = target.createGraphics();
        g.drawImage(source, 0, 0, null);
        g.dispose();
        return target;
    public static ColorModel getColorModel(Image image) {
        try {
            PixelGrabber pg = new PixelGrabber(image, 0,0,1,1, false);
            pg.grabPixels();
            return pg.getColorModel();
        } catch (InterruptedException e) {
            throw new RuntimeException("Unexpected interruption", e);
    public static BufferedImage createBufferedImage(ColorModel cm, int w, int h) {
        WritableRaster raster = cm.createCompatibleWritableRaster(w, h);
        boolean isRasterPremultiplied = cm.isAlphaPremultiplied();
        return new BufferedImage(cm, raster, isRasterPremultiplied, null);
    //you may want to use MediaTracker directly
    public static Image load(Image image) {
        ImageIcon ii = new ImageIcon(image);
        if (ii.getImageLoadStatus() != MediaTracker.COMPLETE)
            throw new IllegalArgumentException("unable to load image");
        return image;
    //demo
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://developers.sun.com/im/logo_java.gif");
        Image image = Toolkit.getDefaultToolkit().createImage(url);
        load(image);
        BufferedImage bi1 = toBufferedImage(image);
        BufferedImage bi2 = toBufferedImage(image, BufferedImage.TYPE_INT_RGB);
        JPanel cp = new JPanel();
        cp.add(createLabel(image, "original"));
        cp.add(createLabel(bi1, "buffered 1"));
        cp.add(createLabel(bi2, "buffered 2"));
        JFrame f = new JFrame("X");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(cp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    //demo
    static JLabel createLabel(Image image, String title) {
        JLabel label = new JLabel(new ImageIcon(image));
        label.setBorder(BorderFactory.createTitledBorder(title));
        return label;
}I give two versions of toBufferedImage: one takes just an Image and creates a BufferedImage with
the same ColorModel. That is usually what you want, if you care. The second creates a BufferedImage
of a given type, like TYPE_BYTE_INDEXED.

Similar Messages

  • How can I convert an Image ( or BufferedImage ) to Base64 format ?

    Hi folks...
    How can I convert an Image, or BufferedImage, to the Base64 format ?
    The image that I want to convert, I get from the webCam connected to the computer...
    Anyone can help me ?
    Rodrigo Kerkhoff

    I suggest you read this thread concerning this:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=477461
    Failing that, Google is your friend.
    Good luck!

  • Loading a raw image in BufferedImage

    Hi guys,
    I'm very new to java .I have a raw image which has 32 bit pixels which has ABGR...with alpha as the most signficant byte and the red as the least significant byte. I have an array of ints and I want to load this to a BufferedImage object. I then use a JPanel and render the BufferedImage on to it. I tried doing with other file formats like jpg , gifs and so the rendering to the JPanel works fine. But I'm not able to get the array of ints to be stored in BufferedImage correctly. Could you please let me know what I did was wrong or any suggestions?
    Currently I have a class called RGBAImage that reads the raw image and stores it as an array of ints.
    So in order to create a BufferedImage I do this roughly,
    DataBufferInt buffer = new DataBufferInt(img.getPixels() , img.getPixels().length) ;
    //                                                        bits  red                   green                   blue                 alpha
    ColorModel cm = new DirectColorModel(32, (int)0x000000ff , (int)0x0000ff00 , (int)0x00ff0000 , (int)0xff000000) ;
    SampleModel sm = cm.createCompatibleSampleModel(img.getWidth , img.getHeight) ;
    WriteableRaster raster = Raster.createWritableRaster(sm , buffer , null) ;
    BufferedImage bimg = new BufferedImage(cm , raster , false , null) ;Is this how its to be done? I am not getting the image drawn on the panel. Any suggestions or links?
    Thank you
    Siddharth

    I have an array of ints and I want to load this to a BufferedImage object.In your sample code I cannot see how the int array you are talking about becomes the image data. Also, what is the img variable? Please provide a more complete code sample.

  • Image to bufferedImage takes several minutes

    Hi,
    In my program I try to convert java.awt.Image to java.awt.image.BufferedImage:
    public static BufferedImage image2BufferedImage(Image img,int w,int h){
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(img, 0,0,w, h, null);
    g2d.dispose();
    return bi;
    When the image is large, g2d.drawImage(...) takes several minutes. Someone can say me what's happen?

    How i can do it?
    maybe (java -Xmx125M ...)I use: java -Xmx300M
    Did it work?

  • Extracting image from bufferedimage based on colors

    Hi everyone,
    i have a rather tricky problem: Is it possible to extract an image from a bufferedimage depending on colors. I have images with a black/dark gray item on a mostly white background and need to extract (sub)images of both ends of that item, which is displayed basically horizontally across the iamge.

    yes you can do this no problem
    convert image to pixels (array)
    traverse the array and look for the desired color (threshold)
    when you find a pixel you like, copy it to the new (sub) image or whatever

  • How to transfer image into BufferedImage?

    Hi everyone,
    I tried looking for such a solution, however, I can't get any API to do this.
    Anyone knows how to achieve it? thanks
    David

    You wanted to copy an Image's contents to a BufferedImage, right?
    So you have something like this:
    Image myImage = ...
    BufferedImage buffImg = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB); //...or whatever
    buffImg.getGraphics().drawImage( myImage, 0, 0, Color.BLACK, null);
    ...

  • Convert Image to BufferedImage

    how do i convert an Image object
    i) To a BufferedImage object
    2) To a RenderedImage object

    I tested the following code for copying a tif image onto clipboard and then pasting it on MSWord. It works fine, I have not tried the other way
    import java.awt.image.RenderedImage;
    import java.io.IOException;
    import javax.media.jai.RenderedImageAdapter;
    import util.TIFFFileHelper;
    public class ClipboardSupport implements ClipboardOwner{
         public ClipboardSupport() {
              super();
         public static void main(String[] args) throws IOException {
              ClipboardSupport co = new ClipboardSupport();
              RenderedImage img=co.getTestImage();
              co.copyToClipBoard(img);
         private RenderedImage getTestImage() throws IOException{
              TIFFFileHelper th = new TIFFFileHelper("C:/workspace/AV/src/images/onepageSample.tif");
              th.getPageCountParseFirstPage();
              RenderedImage img = th.getFirstPage();
              return img;
         public void copyToClipBoard(RenderedImage img2){
              Image img=this.getCovertedImage(img2);
              this.copyToClipBoard(img);
         public void copyToClipBoard(Image img){
              Toolkit tkt = Toolkit.getDefaultToolkit();
              Clipboard clipboard = tkt.getSystemClipboard();
              Transferable t = new ImageSelection(img);
              clipboard.setContents(t,this);
         public void lostOwnership(Clipboard clipboard, Transferable contents) {
              System.out.println("ClipboardSupport.lostOwnership() called");
         private Image getCovertedImage(RenderedImage img) {
              RenderedImageAdapter aid = new RenderedImageAdapter(img);
              Image im = aid.getAsBufferedImage();
              return im;
    package util.clipboard;
    import java.awt.Image;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.io.IOException;
    public class ImageSelection implements Transferable {
         private Image img=null;
         DataFlavor dataFlavor = DataFlavor.imageFlavor;
         public ImageSelection(Image img) {
              super();
              this.img=img;
         public DataFlavor[] getTransferDataFlavors() {          
              DataFlavor[] data = new DataFlavor[1];
              data[0]=dataFlavor;
              return data;
         public boolean isDataFlavorSupported(DataFlavor flavor) {          
              if(dataFlavor.equals(flavor)){
                   return true;
              }else{
                   return false;
         public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
              return img;
    }

  • How convert Image in BufferedImage?

    Hello i have a simple problem.
    I have a Image and I would want to convert it in BufferedImage format.
    Thanks

    since I had the code anyway:
         public static BufferedImage getBufferedImage(Image img) {
              // if the image is already a BufferedImage, cast and return it
              if((img instanceof BufferedImage) && background == null) {
                   return (BufferedImage)img;
              // otherwise, create a new BufferedImage and draw the original
              // image on it
              int w = img.getWidth(null);
              int h = img.getHeight(null);
              BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2d = bi.createGraphics();
              g2d.drawImage(img, 0, 0, w, h, null);
              g2d.dispose();
              return bi;
         }

  • Write Image into BufferedImage?

    Hi to everyone
    Do anyone advise me on how to write to Image and cast it to the BufferedImage?
    I'm facing the nullPointerException when i use the MemoryImageSource.
    Any help will be appreciated. Thank You
    public void getImage()
              try{
                   int w = ((Integer)oin.readObject()).intValue();
                   System.out.println("Width: " + w);
                   int h = ((Integer)oin.readObject()).intValue();
                   System.out.println("Width: " + h);
                   int [] buffer = (int[])oin.readObject();
                   System.out.println("Width: " + buffer);
                   MemoryImageSource ms = new MemoryImageSource(w, h, buffer, 0, 0);
                   ms.createImage();
              }catch(Exception e)     {
                   System.err.println("Receiving failed: "+ e);
         }

    hey knucklehead, the answer is back at your other post.

  • Draw to Image like BufferedImage.createGraphics(), but NOT in FX2's thread

    Hi. I want to draw some shapes in fx2's Image. Canvas.shapshot() can not be run outside fx's own thread, what gives various trouble, like either out of order drawing or delays on semaphores, On top of that, the code is complex and slow -- all drawing is performed probably on just a single thread, and the app starts to behave suspiciously, like a snapshot to an image within Platform.runLater results in that image drawn elsewhere by fx2 as if it were transparent, even that the image should never be transparent.
    Is fx2 currently not able to do any concurrent plain drawing?

    >
    Is fx2 currently not able to do any concurrent plain drawing?Yes, this is currently the case. To my opinion this is a serious shortcoming of JFX2 which I have complained about already several times but nobody seems to care (except you :-)).
    Michael

  • How to convert BufferedImage back to Image

    I have an Image from ImageIcon and i want to cut it using BufferedImage.getSubImage(...) and now from BufferedImage i want to turn it to Image again so that i can put in ImageIcon.
    Here is my code:
    URL img = new URL(location);
    ImageIcon imgIcon = new ImageIcon(img);
    Image image = imgIcon.getImage();
    //turn image into bufferedImage via graphic draw
    BufferedImage bi = new BufferedImage(..);
    Graphics g = bi.createGraphics();
    g.drawImage(image,0,0,null);
    bi.getSubImage(...);
    // how to turn bi back to Image newImage
    any ideas??

    More correctly, BufferedImage extends Image as Image is an abstract class and not an interface.
    Shaun

  • How to set Image equal to BufferedImage?

    Is there a way to set an Image equal to a BufferedImage?
    For example:
    Image myImage;
    BufferedImage myBuffImage;
    myBuffImage = myImage;
    I know this way is not correct but is there any way either directly or indirectly to do such a thing?
    Thanks,
    Every_man

    Hi there Every_man!
    You can use the drawImage method, like this:
    Image myImage;
    BufferedImage myBuffImage;
    Graphics gBuff = myBuffImage.getGraphics();
    And put this in some of your methods, for example the paintmethod:
    public void paint(Graphics g) {
    gBuff.drawImage(myImage,0,0,null);
    Name you have created a bufferedimage out of your image, is that how you wanted it?
    That should do the work, can't test the code right now but let me know if you have any questions!
    Pat

  • Need help on transforming a bufferedimage back to an image

    Hi,
    for a project in school, I need to read in a .jpeg file, transform it to a bufferedimage, getting the pixels. Then I make a new bufferedimage and all the RGB values that are higher then a certain (changeable) contrast value are made white, the other black (so basicly i transform an image to black and white) (with getRGB from colorimage and setRGB to the new bufferedimage)
    But I have trouble to transform the black and white bufferedimage to an image for viewing the image...
    The code for that part is like this:
    public void beeldWeergeven(){
         for (int j=0;j>height;j++){
              for (int i=0;i<width;i++){
                   waarde = zwartwitmatrix[j][i]*255;
                   imagezw.setRGB(i,j,waarde);
         Image zwimage = toImage(imagezw);
         zwimage = null;{
         JFrame frame = new JFrame();
    JLabel label = new JLabel(new ImageIcon(zwimage));
    frame.getContentPane().add(label, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    public static Image toImage(BufferedImage bufferedImage) {
    return Toolkit.getDefaultToolkit().createImage(bufferedImage.getSource());
    When I compile, I always get a nullpointerexception
    I'm not that good at writing java, so if anyone could lend me a hand on this :)

    For the moment (guess you know there are other ways to Black and White anyway):
    for (int j=0;j>height;j++)
    should be
    for (int j=0;j<height;j++)
    possibly??

  • Plz Help me in Image & BufferedImage conversion

    Hello Every One,
    I want to convert a Image object to one of its subclass BufferImage
    Direct conversion is not allowed.
    Image i;//
    BufferedImage bi;
    bi = (BufferedImage)i;
    This is run time exception.
    Please Tell me how can i perform this conversion.
    Thanx in Advance.

    As this FS seems to be for lingerie company "Victoria's Secret" could points be converted to underwear instead of t-shirts?
    Tip: If you're going to post an entire spec you may want to remove the customer's name first.

  • From BufferedImage to faster Image...

    Hello all.
    I have to use JAI, Java2D, & ImageIO to read a TIFF and convert it into a transparent PNG. It results in a BufferedImage, of course. However, I noticed that the BufferedImage does not perform as quickly as the Image that can be created by the Toolkit (or obtained from the ImageIcon). This is true at least for Windows. For example, on Windows, the image is an instance of sun.awt.windows.WImage. However I have to save the image and reload it in order to get this other image
    My question is this: Is there any way to directly convert a BufferedImage to type WImage, or to whatever native Image type exists on a particular platform. Does Java provide such a mechanism? Does anyone know of a way to do this (w/o having to write and re-read the image)?
    Thank you in advance for your input.

    GraphicsConfiguration.getCompatibleImage() gives you this kind of image. Use something like
    Image originalImage = // load your image here
    BufferedImage bI = GraphicsConfiguration.getCompatibleImage();
    Graphics g = bI.getGraphics();
    g.draw(0,0,originalImage,null); // draw old image into new bI
    not sure about the exact method signatures, just what I remember.

Maybe you are looking for