Java 获取图片rgb值 像素矩阵方法

Java 获取图片rgb值 像素矩阵方法

package com.WXAIPhotoAPI;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;


public class DemoTest2 {

    public static void getData(String path) {
        try {
            int[] rgb = new int[3];
            BufferedImage bimg = ImageIO.read(new File(path));
            int[][] data = new int[bimg.getWidth()][bimg.getHeight()];
            //方式一:通过getRGB()方式获得像素矩阵
            //此方式为沿Height方向扫描
            for (int i = 0; i < bimg.getWidth(); i++) {
                for (int j = 0; j < bimg.getHeight(); j++) {

                    int pixel = bimg.getRGB(i, j);
                    //输出一列数据比对
                    if (i == 0) {
                        rgb[0] = (pixel & 0xff0000) >> 16;
                        rgb[1] = (pixel & 0xff00) >> 8;
                        rgb[2] = (pixel & 0xff);
                        System.out.println("i=" + i + ",j=" + j + ":(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")");
                        int gray = (int) (rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11);    //计算灰度值
                        System.out.println(gray);
                    }

                }
            }


//            Raster raster = bimg.getData();
//            int[] temp = new int[raster.getWidth() * raster.getHeight() * raster.getNumBands()];
//            //方式二:通过getPixels()方式获得像素矩阵
//            //此方式为沿Width方向扫描
//            int[] pixels = raster.getPixels(0, 0, raster.getWidth(), raster.getHeight(), temp);
//            for (int i = 0; i < pixels.length; ) {
//                //输出一列数据比对
//                if ((i % raster.getWidth() * raster.getNumBands()) == 0)
//                    System.out.printf("ff%x%x%x\t", pixels[i], pixels[i + 1], pixels[i + 2]);
//                i += 3;
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        getData("/tmp/1.jpg");
    }

}

 

posted on 2022-04-27 14:34  星河赵  阅读(789)  评论(0编辑  收藏  举报

导航