By overriding the method toByteArray()
, returning the buf
itself (not copying), you can avoid memory related problems. This will share the same array, and not creating another of the correct size. The important thing is to use the size()
method in order to control the number of valid bytes into the array.
final ByteArrayOutputStream output = new ByteArrayOutputStream() {
@Override
public synchronized byte[] toByteArray() {
return this.buf;
}
};
ImageIO.write(image, "png", output);
return new ByteArrayInputStream(output.toByteArray(), 0, output.size());