如何将BufferedImage转换为InputStream? [重复]

问题描述 投票:13回答:4

此问题已经在这里有了答案:

我正在使用servlet上传图像。为了执行调整大小的操作,我将InputStream转换为BufferedImage。现在我想将其保存在mongoDB中。因为据我所知,我是mongoDB的新手,所以GridFS采用InputStream。

所以,有什么方法可以将BufferedImage转换为InputStream吗?

java inputstream bufferedimage
4个回答
12
投票

您需要使用ByteArrayOutputStream将BufferedImage保存到ByteArrayOutputStream,然后从ImageIO class创建一个ImageIO


9
投票

[ByteArrayInputStreamByteArrayInputStreamtoByteArray()BufferedImage

使用ByteArrayOutputStream方法将byte[](它是ByteArrayInputStream)变成ImageIO.write。从那里得到一个字节数组(ImageIO.write),将其馈送到类型为BufferedImageBufferedImage中。

RenderedImage

RenderedImageByteArrayOutputStream都实现ByteArrayOutputStream。因此,您可以方便地使用byte[]语法将其自动关闭。


8
投票

首先,您必须获取您的“字节”:

InputStream

然后使用ByteArrayInputStream(byte [] buf)构造函数创建您的InputStream;


1
投票

通过重写方法InputStream,返回ByteArrayInputStream本身(不进行复制),可以避免与内存相关的问题。这将共享同一数组,而不创建另一个正确大小的数组。重要的是要使用ByteArrayInputStream方法来控制进入数组的有效字节数。

ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(buffImage, "jpeg", os);                          // Passing: ​(RenderedImage im, String formatName, OutputStream output)
InputStream is = new ByteArrayInputStream(os.toByteArray());
© www.soinside.com 2019 - 2024. All rights reserved.