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

重映射是根据颜色重映射表转换图像中的颜色的过程。 颜色重映射表是一个 ColorMap 对象数组。 该数组中的每个 ColorMap 对象都有一个 OldColor 属性和一个 NewColor 属性。

当 GDI+ 绘制图像时,会将图像的每个像素与旧的颜色数组进行比较。 如果像素的颜色与旧的颜色匹配,则其颜色将更改为相应的新颜色。 颜色仅在渲染时更改 - 图像本身(存储在 ImageBitmap 对象中)的颜色值不会更改。

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

示例

以下示例从文件 RemapInput.bmp 创建 Image 对象。 该代码创建由单个 ColorMap 对象组成的颜色重映射表。 ColorRemap 对象的 OldColor 属性为红色,NewColor 属性为蓝色。 图像在不重映射的情况下绘制一次,在重映射的情况下绘制一次。 重映射过程会将所有红色像素更改为蓝色。

下图左侧显示原始图像,右侧显示重映射后的图像。

Screenshot showing the original image and the remapped image.

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);
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)

编译代码

前面的示例专用于 Windows 窗体,它需要 PaintEventArgse,后者是 Paint 事件处理程序的参数。

另请参阅