Search code examples
javaimagefilebufferedimageimagej

Create a set of image files from a byte matrix


As I wrote in the title I would like to understand how to create some images from an array that contains bytes. This is what has been written so far

        BufferedImage arrayImage[] = new BufferedImage [depthV];
        int arrayIndex = 0;
        for (int z = 0; z < depthV; z++)
        {
            byte byteToImg[] = new byte [widthV*heightV];
            for (int x = 0; x < widthV; x++) 
            {
                for (int y = 0; y < heightV; y++) 
                {
                     byteToImg[x + y] = data3D[0][z][y][x];
                }
            }
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteToImg);
            BufferedImage finalImage= null;
            try {
                finalImage = ImageIO.read(byteIn);
            } catch (IOException e) {

                e.printStackTrace();
            }
            arrayImage[arrayIndex]=finalImage;
            arrayIndex++;
        }
        for (int i = 0; i < arrayImage.length; i++) 
        {
            File outputfile = new File("./Resources/tmp/image"+i+".jpg");
            try {
                ImageIO.write(arrayImage[i], "jpg", outputfile);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

The Java function ends with a java.lang.IllegalArgumentException: image == null! What is my error? How I can avoid this issue? Is there a better way to do this?


Solution

  • The SCIFIO library, bundled with ImageJ, can do this easily:

    import io.scif.gui.AWTImageTools;
    ...
    byte[] bytes = new byte[width * height];
    ...
    boolean signed = false;
    BufferedImage bi = AWTImageTools.makeImage(bytes, width, height, signed);
    

    The source code for that method is here (which calls here, which calls here).

    But actually you don't need to use BufferedImage at all if you use SCIFIO and/or ImageJ. See this tutorial for an example of how to write out image planes.

    SCIFIO is available from the ImageJ Maven repository. The relevant pom.xml snippets are:

    <repositories>
        <repository>
            <id>imagej.public</id>
            <url>http://maven.imagej.net/content/groups/public</url>
        </repository>
    </repositories>
    ...
    <dependency>
        <groupId>io.scif</groupId>
        <artifactId>scifio</artifactId>
        <version>0.22.0</version>
    </dependency>