8,731
社区成员
发帖
与我相关
我的任务
分享
<ef:ColorToneEffect x:Key="GrayEffect" LightColor="Transparent" DarkColor="Black" Desaturation="0" ToneAmount="1"/>
你的代码适合用在winform里。而WPF 可以通过前台的标记语言达到不用后台代码实现视觉效果。在通过绑定耦合前后台。 private void GrayImage(string fileName)
{
Bitmap bitmap = (Bitmap)Bitmap.FromFile(fileName, false);
if (bitmap != null)
{
//位图矩形
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height);
//以可读写的方式将图像数据锁定
System.Drawing.Imaging.BitmapData bmpdata = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
//得到图形在内存中的首地址
IntPtr ptr = bmpdata.Scan0;
//构造一个位图数组进行数据存储
int bytes = bitmap.Width * bitmap.Height * 4;
byte[] rgbvalues = new byte[bytes];
//将被锁定的位图数据复制到该数组内
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbvalues, 0, bytes);
//对每一个像素的颜色进行灰度化
double colortemp = 0;
for (int i = 0; i < rgbvalues.Length; i += 4)
{
colortemp = rgbvalues[i + 2] * 0.299 + rgbvalues[i + 1] * 0.587 + rgbvalues[i] * 0.114;
rgbvalues[i] = rgbvalues[i + 1] = rgbvalues[i + 2] = (byte)colortemp;
}
//把处理后的图像数组复制回图像
System.Runtime.InteropServices.Marshal.Copy(rgbvalues, 0, ptr, bytes);
//解锁位图像素
bitmap.UnlockBits(bmpdata);
}
bitmap.Save("test.png");
}