方法: カラー リマップ テーブルを使用する
再マップとは、カラー リマップ テーブルにしたがって画像の色を変換する処理のことです。 カラー リマップ テーブルは、ColorMap オブジェクトの配列です。 配列内の各 ColorMap オブジェクトには、OldColor プロパティと NewColor プロパティがあります。
GDI+ によって画像が描画されるときに、画像の各ピクセルは古い色の配列と比較されます。 ピクセルの色が古い色と一致した場合、その色は対応する新しい色に変更されます。 色が変更されるのはレンダリング時のみで、画像自体の色の値 (Image または Bitmap オブジェクトに格納されています) は変更されません。
再マップされた画像を描画するには、ColorMap オブジェクトの配列を初期化します。 その配列を ImageAttributes オブジェクトの SetRemapTable メソッドに渡し、さらに ImageAttributes オブジェクトを Graphics オブジェクトの DrawImage メソッドに渡します。
例
次の例では、RemapInput.bmp というファイルから Image オブジェクトを作成します。 このコードにより、1 つの ColorMap オブジェクトで構成されるカラー リマップ テーブルが作成されます。 ColorRemap
オブジェクトの OldColor プロパティは赤、NewColor プロパティは青です。 画像は再マップなしで 1 回、再マップありで 1 回描画されます。 再マップ プロセスにより、すべての赤色のピクセルが青色に変更されます。
次の図は、左側に元の画像、右側に再マップ後の画像を示したものです。
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 フォームで使用するために設計されていて、Paint イベント ハンドラーのパラメーターである PaintEventArgs e
を必要とします。
関連項目
.NET Desktop feedback