Java BufferImage 獲取像素矩陣 或 數組


 

參考地址:

https://blog.csdn.net/u013248535/article/details/53929605/

 

   private static int WHITE = new Color(255, 255, 255).getRGB();

    private static int BLACK = new Color(0, 0, 0).getRGB();

  /**
     * 文件轉 int[]數組
     * @param file
     * @return
     */
    public static int[] fileToIntArray(File file){
        try {
            BufferedImage image = ImageIO.read(file);
            int width = image.getWidth();
            int height = image.getHeight();
            return bufferedImageToIntArray(image, width, height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * BufferedImage轉 int[]數組
     * @param file
     * @return
     */
    public static int[] bufferedImageToIntArray(BufferedImage image, int width, int height){
        try {
            int rgb = 0;
            int[] data = new int[width * height];
            // 方式一:通過getRGB()方式獲得像素數組
            // 此方式為沿Height方向掃描
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    rgb = image.getRGB(i, j);
                    if(rgb == -1){
                        //白色
                        data[i + j * width] = WHITE;
                    } else {
                        //黑色
                        data[i + j * width] = BLACK;
                    }
                    //System.out.print(data[i + j * width]+" ");
                }
                //System.out.println();
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM