方式一:
//方式一:通过getRGB()方式获得像素矩阵
public static void getPicArrayData(String path){try{BufferedImage bimg = ImageIO.read(new File(path));int [][] data = new int[bimg.getWidth()][bimg.getHeight()];for(int i=0;i<bimg.getWidth();i++){for(int j=0;j<bimg.getHeight();j++){data[i][j]=bimg.getRGB(i,j);//输出一列数据比对if(i==0){String format = String.format("%x", data[i][j]);System.out.println(format);}}}}catch (IOException e){e.printStackTrace();}
}
方式二:
private static int[][] convertTo2DWithoutUsingGetRGB(String path) throws IOException {BufferedImage image = ImageIO.read(new File(path));final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();final int width = image.getWidth();final int height = image.getHeight();final boolean hasAlphaChannel = image.getAlphaRaster() != null;int[][] result = new int[height][width];if (hasAlphaChannel) {final int pixelLength = 4;for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {int argb = 0;argb += (((int) pixels[pixel] & 0xff) << 24); // alphaargb += ((int) pixels[pixel + 1] & 0xff); // blueargb += (((int) pixels[pixel + 2] & 0xff) << 8); // greenargb += (((int) pixels[pixel + 3] & 0xff) << 16); // redresult[row][col] = argb;col++;if (col == width) {col = 0;row++;}}} else {final int pixelLength = 3;for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {int argb = 0;argb += -16777216; // 255 alphaargb += ((int) pixels[pixel] & 0xff); // blueargb += (((int) pixels[pixel + 1] & 0xff) << 8); // greenargb += (((int) pixels[pixel + 2] & 0xff) << 16); // redresult[row][col] = argb;col++;if (col == width) {col = 0;row++;}}}return result;
}
测试:
public static void main(String[] args) throws IOException {//方式一//getPicArrayData("C:\\Users\\yanni\\Desktop\\企鹅.jpg");//方式二int[][] ints = convertTo2DWithoutUsingGetRGB("C:\\\\Users\\\\yanni\\\\Desktop\\\\企鹅.jpg");for (int i=0;i<ints.length;i++){for (int j=0;j<ints[i].length;j++){//只打印一列数据if (i==0){String format = String.format("%x", ints[i][j]);System.out.println(format);}}}
}
听说第二种方式的性能高出第一种90%,性能更优。
参考:https://www.itranslater.com/qa/details/2325735804238300160