如何将BufferedImage转换为InputStream?
我正在使用servlet上传图像。 要执行resize操作,我将InputStream转换为BufferedImage。 现在我想将它保存在mongoDB中。 因为,据我所知,我是mongoDB的新手,GridFS采用InputStream。
那么,有没有办法将BufferedImage转换为InputStream?
您需要使用ImageIO
类将BufferedImage保存到ByteArrayOutputStream
,然后从toByteArray()
创建ByteArrayInputStream
。
首先,你必须得到你的“字节”:
byte[] buffer = ((DataBufferByte)(bufferedImage).getRaster().getDataBuffer()).getData();
然后使用ByteArrayInputStream(byte [] buf)构造函数创建InputStream;
试试这个
ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(buffImage, "jpg", os); InputStream is = new ByteArrayInputStream(os.toByteArray());
通过重写方法toByteArray()
,返回buf
本身(不复制),可以避免与内存相关的问题。 这将共享相同的数组,而不是创建另一个正确的大小。 重要的是使用size()
方法来控制进入数组的有效字节数。
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());