Java:BufferedImage 到字节数组并返回

标签 java arrays byte bufferedimage

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

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

    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。

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

最佳答案

建议转成字节数组

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

关于Java:BufferedImage 到字节数组并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15414259/

相关文章:

java - 破坏二进制文件

java - 使用 Java 将十六进制 header 信息添加到 JPEG 文件

java - 我正在尝试执行 jql 查询,但出现错误

java - Liferay 以编程方式设置页面布局权限

php - 如何 "rtrim"一个 PHP 数组(仅删除数组末尾的空元素)并尽可能避免 for 或类似循环

python - 使用由整数 [0,...,L-1] 索引的额外列将 numpy 数组 (N,M,L) 转换为 (N*L,M+1)

java - JDBC 中的批量插入 - 单个事务会慢多少?

java - 预期 BEGIN_ARRAY 但在第 1 行第 1 列路径 $ GSON 处为 STRING

python - 如何将原始字节作为参数提供给 C 程序

java - 如何将整数的 "word"表示形式写入 Java 中的文件?