(特别申明:1、如若转载请标明出处http://blog.csdn.net/gufengcangying。
2、 如若雷同,算我抄你!)
在文章(一)的基础上面添加按钮控件,并设置其相应的属性。
如下Form1.Designer.cs中显示其属性:
//
// memory
//
this.memory.Location = new System.Drawing.Point(37, 246);
this.memory.Name = "memory";
this.memory.Size = new System.Drawing.Size(75, 23);
this.memory.TabIndex = 4;
this.memory.Text = "内存法";
this.memory.UseVisualStyleBackColor = true;
this.memory.Visible =true;
this.memory.Click += new System.EventHandler(this.memory_Click);
单击该按钮,添加如下代码:
/// <summary>
/// 内存法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void memory_Click(object sender, EventArgs e)
{
if(curBitmap!=null)
{
//位图矩形
Rectangle rect = new Rectangle(0,0,curBitmap.Width,curBitmap.Height);
//以可读写的方式锁定全部位图像素;
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect,
System.Drawing.Imaging.ImageLockMode.ReadWrite,
curBitmap.PixelFormat);
//得到首地址
IntPtr ptr = bmpData.Scan0;
//24位bmp位图的字节数
int bytes = curBitmap.Width * curBitmap.Height*3;
//定义位图数组
byte[] rgbValues=new byte[bytes];
//复制被锁定的位图像素值到rgbValues数组内;
System.Runtime.InteropServices.Marshal.Copy(ptr,rgbValues,0,bytes);
double colorTemp = 0;
//灰度化处理
for (int i = 0; i < rgbValues.Length;i+=3 )
{
//计算出灰度值
colorTemp = rgbValues[i + 2] * 0.299 + rgbValues[i + 1] * 0.587 + rgbValues[i] * 0.144;
//令R=G=B;
rgbValues[i] = rgbValues[i + 1] = rgbValues[i + 2] = (byte)colorTemp;
}
//复制回位图;
System.Runtime.InteropServices.Marshal.Copy(rgbValues,0,ptr,bytes);
//解锁;
curBitmap.UnlockBits(bmpData);
//对窗体重新绘制,并强制执行Paint事件处理程序;
Invalidate();
}
}
其运行结果如下图所示: