//打开图片
//创建OpenFileDialog对象
OpenFileDialog openFileDialog = new OpenFileDialog();
//创建一个筛选器
openFileDialog.Filter = "jpeg文件|*.jpg";
//设置对话框标题
openFileDialog.Title = "打开图片:";
//启用帮助按钮
openFileDialog.ShowHelp = true;
//如果结果为打开,则选定文件
if (openFileDialog.ShowDialog()==DialogResult.OK)
{
curFileName = openFileDialog.FileName;
curBitmap = (Bitmap)Image.FromFile(curFileName);
Invalidate();
}
//内存法
//内存法
if (curBitmap!=null)
{
//图像矩形
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
//以读写的方式锁定全部位图像素
BitmapData bmpData = curBitmap.LockBits(rect, ImageLockMode.ReadWrite, curBitmap.PixelFormat);
//得到首地址
IntPtr ptr = bmpData.Scan0;
//24位图字节数
int bytes = curBitmap.Width * curBitmap.Height * 3;
//定义位图数组
byte[] rgbValue = new byte[bytes];
//复制被锁定是图像到该数组内
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValue, 0, bytes);
//灰度化
double colorTemp = 0;
for (int i = 0; i < rgbValue.Length; i += 3)
{
//利用公式计算灰度值
colorTemp = rgbValue[i + 2] * 0.299 + rgbValue[i + 1] * 0.589 + rgbValue[i] * 0.114;
//R=G=B
rgbValue[i] = rgbValue[i + 1] = rgbValue[i + 2] = (byte)colorTemp;
}
//把数组复制回位图
System.Runtime.InteropServices.Marshal.Copy(rgbValue, 0, ptr, bytes);
//解锁位图像素
curBitmap.UnlockBits(bmpData);
Invalidate();
}
在Paint事件中写下如下代码
//展示图像Paint
Graphics graphics = e.Graphics;
if (curBitmap != null)
{
graphics.DrawImage(curBitmap, 160, 20, curBitmap.Width, curBitmap.Height);
}