Here you can find the source of toByteArray(Image img)
public static byte[] toByteArray(Image img) throws IOException
//package com.java2s; //License from project: LGPL import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Iterator; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.MemoryCacheImageOutputStream; import javax.swing.ImageIcon; public class Main { public static byte[] toByteArray(Image img) throws IOException { ImageIcon ii = new ImageIcon(img); img = ii.getImage();/* w w w .ja v a 2 s .c om*/ // img eh o seu objeto image BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bi.createGraphics(); g2.drawImage(img, 0, 0, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); MemoryCacheImageOutputStream mos = new MemoryCacheImageOutputStream(baos); Object[] obj = getWriter(1); if (obj == null) return null; ImageWriter writer = (ImageWriter) obj[0]; ImageWriteParam iwp = (ImageWriteParam) obj[1]; writer.setOutput(mos); IIOImage image = new IIOImage(toBufferedImage(img), null, null); writer.write(null, image, iwp); return baos.toByteArray(); } private static Object[] getWriter(float quality) { Object[] obj = new Object[2]; Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg"); if (iter.hasNext()) { ImageWriter writer = iter.next(); ImageWriteParam iwp = writer.getDefaultWriteParam(); iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwp.setCompressionQuality(quality); obj[0] = writer; obj[1] = iwp; return obj; } return null; } public static BufferedImage toBufferedImage(Image img) { ImageIcon ii = new ImageIcon(img); img = ii.getImage(); BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.drawImage(img, 0, 0, null); g.dispose(); return bi; } }