Bitmap对象封装了GDI+中的一个位图,此位图由图形图像及其属性的像素数据组成。因此 Bitmap是用于处理由像素数据定义的图像的对象。
Bitmap类类的主要方法和属性如下:
Lockbits方法的定义如下:
public BitmapData LockBits(rectangle rect,ImageLockMode flag,PixelFormat format);
Lockbits矩形参数Rectangle定义了要在系统内存中锁定的位图的一部分;
Image Lockmode枚举提供了对数据的访问方式,表2.1所示是它的成员;
private void Button1_Click(System.Object sender, System.EventArgs e)
{
try
{
// Retrieve the image.
image1 = new Bitmap(@"C:\Documents and Settings\All Users\"
+ @"Documents\My Music\music.bmp", true);
int x, y;
// Loop through the images pixels to reset color.
for(x=0; x<image1.Width; x++)
{
for(y=0; y<image1.Height; y++)
{
Color pixelColor = image1.GetPixel(x, y);
Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
image1.SetPixel(x, y, newColor);
}
}
// Set the PictureBox to display the image.
PictureBox1.Image = image1;
// Display the pixel format in Label1.
Label1.Text = "Pixel format: "+image1.PixelFormat.ToString();
}
catch(ArgumentException)
{
MessageBox.Show("There was an error." +
"Check the path to the image file.");
}
}
Bitmapdata对象指定了位图的属性,如下所示。
如图所示,数组的宽度并不一定等于图像像素数组的宽度,还有一部分未用区域。这是为了提高效率,系统要确定每行的字节数必须为4的倍数。
例如一幅24位、宽为17个像素的图像,它需要每行占有的空间为51(3×17)个字节,但51不是4的倍数,因此还需要补充1个字节,从而使每行的字节数扩展为52(4x13,即 Stride=52),这样就满足了每行字节数是4的倍数的条件。需要扩展多少个字节不仅是由图像的宽度决定,而且还由图像像素的格式决定。
Graphics对象是GDI+的关键所在。许多对象都是由 Graphics类表示的,该类定义了绘制和填充图形对象的方法和属性。一个应用程序只要需要进行绘制或着色,它就必须使用Graphics对象。
Graphics g= pic1.CreatGraphic();
g.DrawLine(Pens.Blue,point1,point2);