代码之家  ›  专栏  ›  技术社区  ›  user405398

如何将BufferedImage转换为InputStream?

  •  11
  • user405398  · 技术社区  · 15 年前

    我正在使用servlet上传图像。要执行调整大小操作,我正在将InputStream转换为BufferedImage。现在我想把它保存在mongoDB中。因为,据我所知,我对mongoDB还不熟悉,GridFS接受InputStream。

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

    4 回复  |  直到 11 年前
        1
  •  12
  •   SLaks    15 年前

    您需要将BufferedImage保存到 ByteArrayOutputStream 使用 ImageIO class ,然后创建 ByteArrayInputStream toByteArray() .

        2
  •  9
  •   Basil Bourque    6 年前

    BufferedImage ➙ ByteArrayOutputStream ➙ byte[] ➙ ByteArrayInputStream

    使用 ImageIO.write 方法使 BufferedImage (这是一个 RenderedImage )变成一个 ByteArrayOutputStream . 从那里得到一个字节数组( 字节[] ),将其输入 InputStream 类型 ByteArrayInputStream .

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

    两者 ByteArrayOutputStream公司 输入流 实施 AutoCloseable . 所以你可以很方便地用 try-with-resources 语法。

        3
  •  8
  •   Edward83    15 年前

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

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

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

        4
  •  1
  •   ronalchn Damien    13 年前

    通过重写方法 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());