当前位置:嗨网首页>书籍在线阅读

16-图像类

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

20.3.1 图像类

GDI+图像处理相关的类主要包括Image、Bitmap和Metafile等。其中Image类是Bitmap和Metafile的抽象基类,Metafile类提供了处理矢量图的功能,Bitmap是用于处理由像素数据定义的图像的对象。

1.Image类

Image类提供了位图和元文件操作的功能方法,Image类是抽象类,它不能被实例化,只能作为基类,但Image类提供了几个静态的方法,我们可以直接通过类名调用这些方法。

(1)FromFile方法:它根据输入的文件名产生一个Image对象,它有两种函数形式。

public static Image FromFile(string filename);
public static Image FromFile(string filename, bool useEmbeddedColorManagement);

(2)FromHBitmap方法:它从一个Windows句柄处创建一个bitmap对象,它也包括两种函数形式。:

public static bitmap fromhbitmap(intptr hbitmap);
public static bitmap fromhbitmap(intptr hbitmap, intptr hpalette);

(3)FromStream方法:从一个数据流中创建一个image对象,它包含三种函数形式。

public static image fromstream(stream stream);
public static image fromstream(stream stream, bool useembeddedcolormanagement);
fromstream(stream stream, bool useembeddedcolormanagement, bool validateimagedata);

2.Metafile类

Metafile类用于定义图形图元文件。图元文件包含描述一系列图形操作的记录,这些操作可以被记 录(构造)和回放(显示)。二维矢量图形是绘图的基本元素(例如,直线、曲线和图形),它们由坐标系统上的一些点和另外一些描述参数指定。元文件中记录表示图形命令序列的矢量图像,Metafile类用于记录、显示和保存元文件。矢量图文件格式主要有图元文件格式 (WMF) 和增强型图元文件格式 (EMF)。

3.Bitmap类

Bitmap是C#中常用的图像类,它封装GDI+位图,此位图由图形图像及其属性的像素数据组成。Bitmap类有多个重载的构造函数。

(1)public Bitmap(Image image) 。

参数image代表一个现有图像对象。

(2)public Bitmap(int width, int height)。

参数width、height分别表示Bitmap图像的宽度和高度。

(3)public Bitmap(String filename )

参数filename表示图像所对应的文件。

(4)public Bitmap(Stream stream )

参数stream表示图像所对应的数据流。

Bitmap类常用属性如下。

  • Height属性:Bitmap图像的高度。
  • Width属性:Bitmap图像的宽度。
  • Size属性:Bitmap图像的宽度和高度。
  • RawFormat属性:Bitmap图像对象的格式。
  • PixelFormat属性:Bitmap图像的像素格式。

Bitmap类的常用方法如下。

  • GetPixel方法:获取图像的指定像素的颜色。
  • SetPixel方法:设置图像的指定像素的颜色。
  • Save方法:将Bitmap对象保存到指定的Stream对象。
  • MakeTransparent方法:使指定的颜色对此 Bitmap 透明。
  • RotateFlip方法:旋转、翻转Bitmap对象。
  • LockBits方法和UnlockBits方法:分别锁定和解锁系统内存中的位图像素。在基于像素点的图像处理方法中使用LockBits和UnlockBits是一个很好的方式,这两种方法可以使我们通过指定像素的范围来控制位图的任意一部分,从而避免了通过循环对位图的像素逐个进行处理,每调用LockBits之后都应该调用一次UnlockBits。