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?