Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Converting a java.awt.Image to byte array.

843807Jan 31 2007 — edited Jan 31 2007
I would like to convert a java.awt.Image to a byte array in the easiest and fastest possible way. I have implemented the following method but is has some serious performance flaws (takes approx 500 ms to execute):
public static byte[] imageToByteArray(Image image) {
      
      MediaTracker tracker = new MediaTracker(new Container());
      tracker.addImage(image, 0);
      try {
          tracker.waitForAll();
      }
      catch(InterruptedException e) { }
      BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), 1);
      Graphics gc = bufferedImage.createGraphics();
      gc.drawImage(image, 0, 0, null);
      
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ImageIO.write(bufferedImage, "jpeg", bos);

      return bos.toByteArray();
}
Does anyone know any easier and faster way to accomplish this?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 28 2007
Added on Jan 31 2007
2 comments
2,117 views