CS Student
CS Student

Reputation: 1633

Compressing a BufferedImage without writing to disk

I'd like to compress a BufferedImage without writing anything to the disk as the images represent frames from a video feed so writing to disk would obviously be too slow.

I looked at ImageIO.write(image, "png", OutputStream) but I can't think of what OutputStream to use to prevent writing the resulting compressed image to disk.

Upvotes: 0

Views: 1176

Answers (1)

Ferrybig
Ferrybig

Reputation: 18824

You can use a ByteArrayOutputStream to write bytes to a byte array:

ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "png", out);
byte[] bytes = out.toByteArray();

After you have done the above, bytes will then hold the data that the image contains.

Notice: a ByteArrayOutputStream is a special input kind of OutputStream, you are not required to close it, but it never hurts if you still do it.

Upvotes: 2

Related Questions