0
点赞
收藏
分享

微信扫一扫

c#将图片灰度化


​​


​​

全栈工程师开发手册 (作者:栾鹏)

​​ c#教程全解​​

c#将图片灰度化,将图片转化为灰度模式图片

测试代码

static void Main()
{
Bitmap b = file2img("test.jpg");
Bitmap bb = img_gray(b);
img2file(bb, "test1.jpg");
}

图片灰度化实现函数,需要允许不安全代码编译

//图片灰度化
public static unsafe Bitmap img_gray(Bitmap curBitmap)
{
int width = curBitmap.Width;
int height = curBitmap.Height;
Bitmap back = new Bitmap(width, height);
byte temp;
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
//这种速度最快
BitmapData bmpData = curBitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);//24位rgb显示一个像素,即一个像素点3个字节,每个字节是BGR分量。Format32bppRgb是用4个字节表示一个像素
byte* ptr = (byte*)(bmpData.Scan0);
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
//ptr[2]为r值,ptr[1]为g值,ptr[0]为b值
temp = (byte)(0.299 * ptr[2] + 0.587 * ptr[1] + 0.114 * ptr[0]);
back.SetPixel(i, j, Color.FromArgb(temp, temp, temp));
ptr += 3; //Format24bppRgb格式每个像素占3字节
}
ptr += bmpData.Stride - bmpData.Width * 3;//每行读取到最后“有用”数据时,跳过未使用空间XX
}
curBitmap.UnlockBits(bmpData);
return back;
}

图片读取和保存函数为

//图片读取
public static Bitmap file2img(string filepath)
{
Bitmap b = new Bitmap(filepath);
return b;
}
//图片生成
public static void img2file(Bitmap b, string filepath)
{
b.Save(filepath);
}


举报

相关推荐

0 条评论