【问题标题】:Java: BufferedImage to byte array and backJava:BufferedImage 到字节数组并返回
【发布时间】:2013-03-03 02:18:49
【问题描述】:

我看到很多人都遇到过类似的问题,但是我还没有尝试找到我正在寻找的确切内容。

所以,我有一个方法可以读取输入图像并将其转换为字节数组:

    File imgPath = new File(ImageName);
    BufferedImage bufferedImage = ImageIO.read(imgPath);
    WritableRaster raster = bufferedImage .getRaster();
    DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

我现在要做的是将其转换回 BufferedImage(我有一个需要此功能的应用程序)。请注意,“test”是字节数组。

    BufferedImage img = ImageIO.read(new ByteArrayInputStream(test));
    File outputfile = new File("src/image.jpg");
    ImageIO.write(img,"jpg",outputfile);

但是,这会返回以下异常:

    Exception in thread "main" java.lang.IllegalArgumentException: im == null!

这是因为 BufferedImage img 为空。我认为这与以下事实有关:在我从 BufferedImage 到字节数组的原始转换中,信息被更改/丢失,因此数据不再被识别为 jpg。

有人对如何解决这个问题有任何建议吗?将不胜感激。

【问题讨论】:

    标签: java arrays byte bufferedimage


    【解决方案1】:

    建议转成字节数组

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(img, "jpg", baos);
    byte[] bytes = baos.toByteArray();
    

    【讨论】:

    • 刷新和关闭不会做任何事情
    • 这里使用jpg有什么特殊原因吗?
    • 如果 close() 没有做任何事情,它本身会调用 flush(),并且有必要在 before toByteArray() 之前调用它,而不是在它之后调用它。
    【解决方案2】:

    请注意,调用 closeflush 将无济于事,您可以通过查看它们的源代码/文档自己了解:

    关闭 ByteArrayOutputStream 无效。

    OutputStream 的 flush 方法什么都不做。

    因此使用这样的东西:

    ByteArrayOutputStream baos = new ByteArrayOutputStream(THINK_ABOUT_SIZE_HINT);
    boolean foundWriter = ImageIO.write(bufferedImage, "jpg", baos);
    assert foundWriter; // Not sure about this... with jpg it may work but other formats ?
    byte[] bytes = baos.toByteArray();
    

    这里有一些关于尺寸提示的链接:

    当然,请务必阅读您正在使用的版本的源代码和文档,不要盲目依赖 SO 答案。

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 2014-07-30
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多