如何:使用颜色重新映射表

更新:2007 年 11 月

再变换是按照颜色再变换表变换图像中的颜色的过程。颜色重新映射表是 ColorMap 对象的数组。该数组中的每个 ColorMap 对象有一个 OldColor 属性和一个 NewColor 属性。

GDI+ 绘制图像时,图像的每个像素都与旧颜色的数组进行比较。如果像素的颜色与旧颜色相匹配,则它的颜色将更改为相应的新颜色。只改变颜色的呈现方式,图像本身的颜色值(存储在 ImageBitmap 对象中)不发生改变。

若要绘制再映射的图像,请初始化 ColorMap 对象的数组。将该数组传递给 ImageAttributes 对象的 SetRemapTable 方法,然后将 ImageAttributes 对象传递给 Graphics 对象的 DrawImage 方法。

示例

下面的示例从 RemapInput.bmp 文件创建 Image 对象。该代码创建由一个 ColorMap 对象组成的颜色重新映射表。ColorRemap 对象的 OldColor 属性为 red,NewColor 属性为 blue。图像被绘制两次,一次不进行再变换,另一次进行再变换。再变换过程将所有的红色像素都更改为蓝色。

下面的插图在左侧显示原来的图像,在右侧显示再变换后的图像。

颜色重新映射

Dim image As New Bitmap("RemapInput.bmp")
Dim imageAttributes As New ImageAttributes()
Dim width As Integer = image.Width
Dim height As Integer = image.Height
Dim colorMap As New ColorMap()

colorMap.OldColor = Color.FromArgb(255, 255, 0, 0) ' opaque red
colorMap.NewColor = Color.FromArgb(255, 0, 0, 255) ' opaque blue
Dim remapTable As ColorMap() = {colorMap}

imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap)

e.Graphics.DrawImage(image, 10, 10, width, height)

' Pass in the destination rectangle (2nd argument), the upper-left corner 
' (3rd and 4th arguments), width (5th argument),  and height (6th 
' argument) of the source rectangle.
e.Graphics.DrawImage( _
   image, _
   New Rectangle(150, 10, width, height), _
   0, 0, _
   width, _
   height, _
   GraphicsUnit.Pixel, _
   imageAttributes)

Image image = new Bitmap("RemapInput.bmp");
ImageAttributes imageAttributes = new ImageAttributes();
int width = image.Width;
int height = image.Height;
ColorMap colorMap = new ColorMap();

colorMap.OldColor = Color.FromArgb(255, 255, 0, 0);  // opaque red
colorMap.NewColor = Color.FromArgb(255, 0, 0, 255);  // opaque blue

ColorMap[] remapTable = { colorMap };

imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

e.Graphics.DrawImage(image, 10, 10, width, height);

e.Graphics.DrawImage(
   image,
   new Rectangle(150, 10, width, height),  // destination rectangle 
   0, 0,        // upper-left corner of source rectangle 
   width,       // width of source rectangle
   height,      // height of source rectangle
   GraphicsUnit.Pixel,
   imageAttributes);

编译代码

前面的示例是为使用 Windows 窗体而设计的,它需要 Paint 事件处理程序的参数 PaintEventArgse。

请参见

其他资源

对图像重新着色

图像、位图和图元文件