gpt4 book ai didi

java - ImageIO 中的异常 "java.lang.IllegalArgumentException: image == null!"

转载 作者:行者123 更新时间:2023-12-01 16:43:02 28 4
gpt4 key购买 nike

我正在尝试从字节数组写入 png 文件。

我的应用程序抛出以下异常“java.lang.IllegalArgumentException:image == null!”在ImageIO中

我使用随机字节数组测试了我的解决方案,如下面的代码片段所示,但仍然抛出异常。

你能帮我确定为什么会抛出它吗?

    import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
public class Main {

public static void main(String[] args) throws IOException {
String fn = new String("C:\\Users\\frogwine\\Desktop\\P1.png");

byte [] data = new byte[256];

Random r = new Random();
r.nextBytes(data);
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ByteArrayInputStream input_stream= new ByteArrayInputStream(data);
BufferedImage final_buffered_image = ImageIO.read(input_stream);
ImageIO.write(final_buffered_image , "png", new File(fn) );
}


}

堆栈跟踪:

    "C:\Program Files\Java\jdk-13.0.1\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.3\lib\idea_rt.jar=57315:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.3\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\frogwine\Documents\deneme\out\production\deneme com.berk.Main
Exception in thread "main" java.lang.IllegalArgumentException: image == null!
at java.desktop/javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at java.desktop/javax.imageio.ImageIO.getWriter(ImageIO.java:1608)
at java.desktop/javax.imageio.ImageIO.write(ImageIO.java:1540)
at com.berk.Main.main(Main.java:23)

Process finished with exit code 1

最佳答案

这并不奇怪。来自ImageIO.read文档:

If no registered ImageReader claims to be able to read the resulting stream, null is returned.

将随机字节写入数组不会创建任何格式的有效图像数据,因为图像格式具有至少由 header 组成的标准结构。因此,ImageIO.read 返回 null。

关于java - ImageIO 中的异常 "java.lang.IllegalArgumentException: image == null!",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59247899/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com