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

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

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

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

示例:

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

下图显示了左侧的原始图像和右侧的重新映射图像。

显示原始图像和重新映射图像的屏幕截图。

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 事件处理程序的参数。

另请参阅