How to get an InputStream from a BufferedImage?

前端 未结 3 1552
后悔当初
后悔当初 2020-12-08 00:05

How can I get an InputStream from a BufferedImage object? I tried this but ImageIO.createImageInputStream() always returns NULL

BufferedImage bigImage = Grap         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 00:46

    By overriding the method toByteArray(), returning the buf itself (not copying), you can avoid memory related problems. This will share the same array, 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());
    

提交回复
热议问题