C# 图片灰度处理

该博客介绍了一种使用C#代码批量将图片转换为灰度的方法,通过遍历像素并应用加权平均值法来确定灰度值。这种方法比使用Word转换效果更佳,适用于大量图片处理需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求

图片需要批量转成灰度,word转换效果不大理想,代码批量处理一下

方法

public Bitmap ImageGrayscale(string imagePath)
{
    Bitmap image = new Bitmap(imagePath);
    Bitmap bitmap = new Bitmap(image.Width, image.Height);
    Color pixel;
    for (int x = 0; x < image.Width; x++)
    {
        for (int y = 0; y < image.Height; y++)
        {
            pixel = image.GetPixel(x, y);
            int r, g, b, Result = 0;
            r = pixel.R;
            g = pixel.G;
            b = pixel.B;
            int iType = 2;
            switch (iType)
            {
                case 0://平均值法
                    Result = ((r + g + b) / 3);
                    break;
                case 1://最大值法
                    Result = r > g ? r : g;
                    Result = Result > b ? Result : b;
                    break;
                case 2://加权平均值法
                    Result = ((int)(0.7 * r) + (int)(0.2 * g) + (int)(0.1 * b));
                    break;
            }
            //pixel.A
            //alpha 分量指定颜色的透明度:0 是完全透明的,255 是完全不透明的。 同样,值为 A 255 表示不透明颜色。 从 A 1 到 254 的值表示半透明颜色。 接近 A 255 时,颜色变得更加不透明。
            bitmap.SetPixel(x, y, Color.FromArgb(pixel.A, Result, Result, Result));
        }
    }
    return bitmap;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值