How to convert BufferedImage to InputStream?

强颜欢笑 提交于 2019-11-30 18:01:12

You need to save the BufferedImage to a ByteArrayOutputStream using the ImageIO class, then create a ByteArrayInputStream from toByteArray().

First of all you must get your "bytes":

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

And then use ByteArrayInputStream(byte[] buf) constructor to create your InputStream;

Sorter

try this

ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(buffImage, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
Igor

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());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!