[java]图片彩色转灰色

灰度化处理有多种处理方式:
1.分量法
2.最大法
3.平均法
4.加权平均法
下面采用的是对R、G、B分量进行加权平均的算法:
0.2989R+ 0.5870G + 0.1140B



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

public class ToGray {


    public static void main(String args[]) throws IOException {

        BufferedImage imgIn = ImageIO.read(new File("test.jpg"));
        int inWith = imgIn.getWidth();
        int inHeight = imgIn.getHeight();
        int imx = imgIn.getMinX();
        int imy = imgIn.getMinY();
        for(int i = imx; i < inWith; i++){
            for(int j = imy; j < inHeight; j++){


                int pixel = imgIn.getRGB(i, j); // 
                int[] rgb = new int[3];
                rgb[0] = (pixel & 0xff0000) >> 16;  //r
                rgb[1] = (pixel & 0xff00) >> 8;  //g
                rgb[2] = (pixel & 0xff);  //b
                //gray = r * 0.299 + g * 0.578 + b* 0.114
                float[] r = new float[3];
                r[0] = (float) (rgb[0]*0.299);
                r[1] = (float) (rgb[0]*0.578);
                r[2] = (float) (rgb[0]*0.114);
                int gray = (int) (r[0] + r[1] + r[2]);


                imgIn.setRGB(i, j, (gray << 16) | (gray << 8) | gray);

            }

        }

        writeToFile(imgIn, "png", new File("out.png"));//写到文件


    }

    public static void writeToFile(BufferedImage image, String format, File file)
            throws IOException {
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }
}

处理前

这里写图片描述

处理后

这里写图片描述

猜你喜欢

转载自blog.csdn.net/yang10560/article/details/77017157