Java- Convert bufferedimage to byte[] without writing to disk

tier1 picture tier1 · Apr 20, 2012 · Viewed 41.4k times · Source

I'm trying to send multiple images over a socket using java but I need a faster way to convert the images to a byte array so I can send them. I tried the following code but it wrote about 10,000 images to my C:\ drive. Is there a way to make this conversion without writing to disk? Thanks!

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                    //ImageIO.setUseCache(false);
                    ImageIO.write(bi.getImage(), "jpg", outputStream);

                    byte[] imageBytes = outputStream.toByteArray();

Answer

stacker picture stacker · Apr 20, 2012

This should work:

byte[] imageBytes = ((DataBufferByte) bufferedImage.getData().getDataBuffer()).getData();