首先设置项目-属性-生成-去掉不允许安全代码
//创建图像
Bitmap image = new Bitmap(path);
//获取图像的BitmapData对像
BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
//循环处理
unsafe
{
byte* ptr = (byte*)(data.Scan0);
byte bitsPerPixel = (byte)Image.GetPixelFormatSize(data.PixelFormat);
for (int x = 0; x <data.Width; x++)
{
for (int y = 0; y < data.Height ; ++y)
{
byte* pdata = ptr + y * data.Stride + x * bitsPerPixel / 8;
///网上很多指针操作图片方式,但都是外层height里层width。无所谓哪个在外层,重点是上面这条语句,取到某行列交叉点的指针
///然后用*(pdata) 、*(pdata + 1) 、*(pdata + 2)对应BGR,注意不是习惯性的RGB
}
}
}
Bitmap result = new Bitmap(image.Width, image.Height, data.Stride, PixelFormat.Format24bppRgb, data.Scan0);
result.Save(dpath);
本文介绍了一种利用C#和Bitmap类处理图像的高效技术,包括图像的加载、锁定位图数据、指针操作进行像素修改,并最终保存为新图像文件的过程。重点在于通过位图数据操作实现对图像的复杂修改,适用于需要直接访问和修改图像像素的应用场景。

326

被折叠的 条评论
为什么被折叠?



