javajavax.imageio

Exception "java.lang.IllegalArgumentException: image == null!" in ImageIO


I'm trying to write a png file from a bytes array.

My application is throwing the following exception "java.lang.IllegalArgumentException: image == null!" in ImageIO

I tested my solution using a random bytes array as you can see in the code snippet below, but the exception still being thrown.

Can you help me to identify why is it being thrown ?

    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) );
        }


    }

Stacktrace:

    "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

Solution

  • Well that's no surprise. From the ImageIO.read documentation:

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

    Writing random bytes to an array is not going to create valid image data in any format, because image formats have a standard structure that consists, at the very least, of a header. For this reason, ImageIO.read returns null.