The Mobile Galaxy The New Mobile Era Has Come | Mobile – A Time To Remember

19Dec/120

How to convert BufferedImage to byte[] in Java?

Method 1 (no cached):

BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.WHITE);
        g.setBackground(Color.WHITE);
        g.clearRect(0, 0, 1, 1);
        AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.0f);
        g.setComposite(ac);
        g.dispose();

        // Kevin 12/18/2012 change for no cached image to bytes[]
        try {

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            JPEGCodec.createJPEGEncoder(baos).encode(image);
            resultImageAsRawBytes = baos.toByteArray(); 
            sLogger.debug("[D] resultImageAsRawBytes is done!!!");

        } catch (Exception e) {
            sLogger.error("[E] resultImageAsRawBytes throw error!!!", e);

        }

Method 2(cached):
        BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.WHITE);
        g.setBackground(Color.WHITE);
        g.clearRect(0, 0, 1, 1);
        AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.0f);
        g.setComposite(ac);
        g.dispose();

        // open
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
	        // write
	        ImageIO.write(image, "gif", baos);
        } catch (IOException ioe) {
            sLogger.error("[I] Image write failed!!!", ioe);

        }
        // flush
        baos.flush();

        resultImageAsRawBytes = baos.toByteArray();

        // close
        baos.close();

For method 2, sometimes will throw exception in some cases because temporary folder.
Share
Tagged as: No Comments