如何在Java中将图像转换为int [] []?

时间:2019-01-14 14:59:20

标签: java image file bufferedimage

我加载了二进制图像,并且想将其转换为2D数组,尤其是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;}

但是当我运行源代码时,会出现异常:

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

你能帮我吗?

1 个答案:

答案 0 :(得分:-1)

如果要获取所有像素为2D数组(矩阵),则可以使用:

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

然后该矩阵的用法很简单:

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.
    }
}

还有其他获取和设置像素的方法,请务必阅读文档。 希望这会有所帮助。