17

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

那么,有没有办法将 BufferedImage 转换为 InputStream 呢?

4

4 回答 4

18

BufferedImageByteArrayOutputStreambyte[]ByteArrayInputStream

使用该ImageIO.write方法将 a BufferedImage(即 a RenderedImage)变为 a ByteArrayOutputStream。从那里得到一个字节数组 ( byte[]),将它输入到InputStreamtypeByteArrayInputStream中。

ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(buffImage, "jpeg", os);                          // Passing: ​(RenderedImage im, String formatName, OutputStream output)
InputStream is = new ByteArrayInputStream(os.toByteArray());

ByteArrayOutputStreamInputStream实施AutoCloseable。_ 因此,您可以使用try-with-resources语法方便地自动关闭它们。

于 2014-02-05T05:21:57.617 回答
12

您需要ByteArrayOutputStream使用ImageIO该类将 BufferedImage 保存到 a 中,然后创建一个ByteArrayInputStreamfrom toByteArray()

于 2010-11-22T23:51:18.740 回答
10

首先你必须得到你的“字节”:

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

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

于 2010-11-22T23:54:39.617 回答
4

通过覆盖方法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());
于 2012-09-03T19:26:34.667 回答