[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);
        }
    }
}

处理前

这里写图片描述

处理后

这里写图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值