CSharp 彩色图像转为灰度图像

本文介绍了一种使用 C# 实现将彩色图片转换为灰度图片的方法。通过定义灰度矩阵并应用到图像属性中,实现了色彩的转换。

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

 

using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;

public class MyClass
{
    
public static void Main()
    
{
        System.Drawing.Bitmap bm 
= new System.Drawing.Bitmap("F:/1寸.jpg");    
        System.Drawing.Imaging.ImageAttributes ia 
= new  System.Drawing.Imaging.ImageAttributes();
        
float[][] grayMatrix = new float[][]{
                                                
new float[]{0.299f,  0.299f,  0.299f,  00},
                                                
new float[]{0.587f0.587f0.587f00},
                                                
new float[]{0.114f0.114f0.114f00},
                                                
new float[]{00010},
                                                
new float[]{00001}
                                            }
;
                                            
                                            
        ColorMatrix cm 
= new ColorMatrix(grayMatrix);

        ia.SetColorMatrix(cm);
        
        Bitmap Target 
= new Bitmap(bm.Width,bm.Height);
        
        WL(
"开始转换!");
        
        
using (Graphics grap = Graphics.FromImage(Target)) {
            grap.DrawImage(bm, 
new Rectangle(00, bm.Width, bm.Height),
                
00, bm.Width, bm.Height,
                GraphicsUnit.Pixel, ia);
        }

        
        WL(
"装换完毕!");
        Target.Save(
"F:/黑白一寸.jpg",ImageFormat.Jpeg);
        RL();
    }

    
    
Helper methods
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值