Search code examples
javaimagefilebufferedimage

How to convert an image to int[][] in java?


I loaded a binary image and I want to convert it to 2D array, in particular int[][]:

public int[][] ImageToArray(String pathImage) throws IOException {

    File file = new File(pathImage);
    BufferedImage bufferedImage = ImageIO.read(file);

    int width = bufferedImage.getWidth();
    int height = bufferedImage.getHeight();
    int[][] imageArray = new int[width][height];

    return imageArray;}

But when I run my source code I get an exception:

Caused by: javax.imageio.IIOException: Can't read input file!

Can you help me?


Solution

  • If you want to get all pixels as 2D array(matrix), you can use:

    File file = new File(pathImage); // Be sure to read input file, you have error reading it.
    BufferedImage bufferedImage = ImageIO.read(file);
    WritableRaster wr = bufferedImage.getRaster();
    

    Then the usage of that matrix would be simple as:

    for (int i = 0; i < wr.getWidth(); i++) {
        for (int j = 0; j < wr.getHeight(); j++) {      
            int pixel = wr.getSample(i, j, 0); // the sample in the specified band for the pixel at the specified coordinate.
        }
    }
    

    There are other methods for getting and setting a pixel, be sure to read docs. Hope this helps.