//打开图片
private void button1_Click(object sender, EventArgs e)
{
//创建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);
byte temp = 0;
//启用不安全模式
unsafe
{
//得到首地址
byte* ptr = (byte*)(bmpData.Scan0);
//二维图像循环
for (int i = 0; i < bmpData.Height; i++)
{
for (int j = 0; j < bmpData.Width; j++)
{
//利用公式计算灰度值
temp = (byte)(ptr[2] * 0.299 + ptr[1] * 0.578 + ptr[0] * 0.114);
//R=G=B
ptr[0] = ptr[1] = ptr[2]=temp;
//指向下一个元素
ptr += 3;
}
//指向下一行数组的首字节
ptr += bmpData.Stride - bmpData.Width * 3;
}
}
//解锁位图像素
curBitmap.UnlockBits(bmpData);
//重绘
Invalidate();
}
在paint事件中写下展示图像的代码
//展示图像Paint
Graphics graphics = e.Graphics;
if (curBitmap != null)
{
graphics.DrawImage(curBitmap, 160, 20, curBitmap.Width, curBitmap.Height);
}