2

I tried many ways for converting an image of Image class to BufferedImage in an applet program. And i got one method which is works fine when running from the netbeans.but same code is not working while running through browser. The code i tried was

ImageIcon icon = new ImageIcon(orgImage);
BufferedImage buffer = ((ToolkitImage) icon.getImage()).getBufferedImage();

also tried the following

1) BufferedImage buffer = ((ToolkitImage) orgImage).getBufferedImage();

2) BufferedImage  buffer = new BufferedImage(
   orgImage.getWidth(null), orgImage.getWidth(null), BufferedImage.TYPE_INT_RGB);
   buffer.getGraphics().drawImage(orgImage, 0, 0, null);

orgImage is a colour image.

buffer is null in all these case..

what is the solution to my problem?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Udanesh N
  • 161
  • 2
  • 2
  • 15
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) `..drawImage(orgImage, 0, 0, null);` should ideally be `drawImage(orgImage, 0, 0, this);` 3) "buffer is null in all these case.."* I do not understand how it could be null in the 2nd case, but an SSCCE should clarify that.. – Andrew Thompson Jul 11 '13 at 20:44

1 Answers1

2

To convert a image to a buffered Image you can use the following function:

/**
 * Converts a given Image into a BufferedImage
 * 
 * @param img The Image to be converted
 * @return The converted BufferedImage
 */
public BufferedImage toBufferedImage(Image img){
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }
    // Create a buffered image with transparency
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();
    // Return the buffered image
    return bimage;
}

Paste it anywhere in your class and use the following code:

BufferedImage bi = toBufferedImage(orgImage);

~Regards Max

Max
  • 792
  • 1
  • 8
  • 20
  • Depending on how it is loaded, `Image` may not be fully realised, meaning that with out some kind of `ImageObserver`, the `drawImage` method may result in not painting anything at all... – MadProgrammer Jul 12 '13 at 05:30
  • if the image is not loaded,it will be null na? – Udanesh N Jul 12 '13 at 10:48
  • i written the code in a thread..the code is written inside an if condition that checks whether the image is null..if still the image is loading that will be null and if will not be executed..when the image is loaded completely,it will enter the if condition and will convert the image.... is my assumption is correct or wrong? – Udanesh N Jul 12 '13 at 10:50