}
}
三、对像素的访问
我们可以来建立一个GrayBitmapData类来做相关的处理。整个类的程序如下:
复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace ImageElf
{
class GrayBitmapData
{
public byte[,] Data;//保存像素矩阵
public int Width;//图像的宽度
public int Height;//图像的高度
public GrayBitmapData()
{
this.Width = 0;
this.Height = 0;
this.Data = null;
}
public GrayBitmapData(Bitmap bmp)
{
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
this.Width = bmpData.Width;
this.Height = bmpData.Height;
Data = new byte[Height, Width];
unsafe
{
byte* ptr = (byte*)bmpData.Scan0.ToPointer();
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++)
{
//将24位的RGB彩色图转换为灰度图
int temp = (int)(0.114 * (*ptr++)) + (int)(0.587 * (*ptr++))+(int)(0.299 * (*ptr++));










