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?

1
  • 1) For better help sooner, post an SSCCE. 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.. Jul 11, 2013 at 20:44

1 Answer 1

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

3
  • 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... Jul 12, 2013 at 5:30
  • if the image is not loaded,it will be null na?
    – Udanesh N
    Jul 12, 2013 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, 2013 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.