使用色彩重新對應表
重新對應是指根據色彩重新對應表轉換影像中色彩的程序。色彩重新對應表是 ColorMap 物件的陣列。陣列中的每一個 ColorMap 物件都具有 OldColor 屬性和 NewColor 屬性。
當 GDI+ 繪製影像時,會將影像中的每一個像素與舊的色彩陣列加以比較。如果像素的色彩與舊的色彩相符,就會將色彩變成對應的新色彩。色彩只有在呈現時會變更-影像本身的色彩值 (儲存在 Image 或 Bitmap 物件中) 不會變更。
若要繪製重新對應的影像,請初始化 ColorMap 物件的陣列。將這個陣列傳遞至 ImageAttributes 物件的 SetRemapTable 方法,然後再將 ImageAttributes 物件傳遞至 Graphics 物件的 DrawImage 方法。
下列範例會從 RemapInput.bmp 檔案建立 Image 物件。程式碼會建立只包含單一 ColorMap 物件的色彩重新對應表。ColorRemap 物件的 OldColor 屬性為紅色,NewColor 屬性為藍色。繪製影像時,一次不含重新對應,一次包含重新對應。重新對應程序會將所有紅色像素變成藍色。
Dim image = 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)
[C#]
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);
下圖左邊顯示的是原始的影像,右邊顯示的是重新對應的影像。