如何将BufferedImage转换为InputStream?
我正在使用 servlet 上传图像。为了执行调整大小操作,我将 InputStream 转换为 BufferedImage。现在我想将它保存在 mongoDB 中。因为据我所知,我是 mongoDB 的新手,GridFS 采用 InputStream。
那么,有没有办法将BufferedImage转换为InputStream呢?
I am uploading images using servlet. To perform resize operations i am converting InputStream to BufferedImage. Now i want to save it in mongoDB. Since, i am new to mongoDB as far as i know, GridFS takes InputStream.
So, is there any way to convert BufferedImage to InputStream?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
BufferedImage
➙ByteArrayOutputStream
➙byte[]
➙ByteArrayInputStream
使用
ImageIO.write
方法来创建BufferedImage
(这是一个RenderedImage
) 到ByteArrayOutputStream< /代码>
。从那里获取一个字节数组(
byte[]
),将其输入到InputStream
类型ByteArrayInputStream
。ByteArrayOutputStream
和InputStream
都实现AutoCloseable
。因此,您可以方便地使用 try-with-resources 语法。BufferedImage
➙ByteArrayOutputStream
➙byte[]
➙ByteArrayInputStream
Use the
ImageIO.write
method to make aBufferedImage
(which is aRenderedImage
) into aByteArrayOutputStream
. From there get a byte array (byte[]
), feeding that into anInputStream
of typeByteArrayInputStream
.Both the
ByteArrayOutputStream
andInputStream
implementAutoCloseable
. So you can conveniently have those closed automatically by using try-with-resources syntax.首先你必须得到你的“字节”:
然后使用ByteArrayInputStream(byte[] buf)构造函数来创建你的InputStream;
First of all you must get your "bytes":
And then use ByteArrayInputStream(byte[] buf) constructor to create your InputStream;
您需要将 BufferedImage 保存到
ByteArrayOutputStream
使用ImageIO
类,然后创建一个ByteArrayInputStream
来自toByteArray()
。You need to save the BufferedImage to a
ByteArrayOutputStream
using theImageIO
class, then create aByteArrayInputStream
fromtoByteArray()
.通过重写方法
toByteArray()
,返回buf
本身(而不是复制),您可以避免与内存相关的问题。这将共享相同的数组,并且不会创建另一个正确大小的数组。重要的是使用size()
方法来控制数组中有效字节的数量。By overriding the method
toByteArray()
, returning thebuf
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 thesize()
method in order to control the number of valid bytes into the array.