final Image image = ...; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { final BufferedImage bufferedImage = createBufferedImageFrom(image); ImageIO.write(bufferedImage, "png", baos); } finally { IOUtils.closeQuietly(baos); } return baos.toByteArray(); private BufferedImage createBufferedImageFrom(final Image image) { if (image instanceof BufferedImage) { return (BufferedImage) image; } else { final BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); final Graphics2D g2 = bi.createGraphics(); g2.drawImage(image, 0, 0, null); return bi; } }
If you don’t want to make use of IOUtils
from Apache Commons Lang, you should you know, the code in the finally
block would be something like
try { if (baos != null) { baos.close(); } } catch (IOException ioe) { // ignore }
Thanks Lot!!!!