Convert Java Image Object to Byte Array
Posted on 2006-03-27
I need to take a java Image object (java.awt.Image) and convert it to a byte array. I need to preserve all of the image information not just the pixels!
Basically I have a database, and I have read the image from the database into a byte array, I have then constructed an Image object from this byte array - this all works fine, I can render the image, manipulate it etc.
But now I need to go the other way and convert the Image object back to a byte array - this doesnt appear to be so easy!
The solution MUST work for both Sun JDK 1.4+ and 1.5+ and MUST NOT rely on any 3rd party libraries unless they are absolutely tiny and open source, although 3rd party libraries are not the prefered method!
The code I had originally found to do this (below) throws an exception at g,drawimage(...), and to be honset I dont understand enough about Java to fix it myself (ths solution does not have to include this code)-
private byte convertImageToByteArray(Image img, String MIMEType)
Iterator iter = ImageIO.getImageWritersByMIMEType(MIMEType);
ImageWriter writer = iter.hasNext() ? (ImageWriter) iter.next() : null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
BufferedImage rendImage = null;
if(img instanceof BufferedImage)
rendImage = (BufferedImage) img;
MediaTracker tracker = new MediaTracker(this);
rendImage = new BufferedImage(img.getWidth(null), img.getHeight(null), 1);
Graphics g = rendImage.createGraphics();
g.drawImage(img, 0, 0, null);
writer.write(new IIOImage(rendImage, null, null));