次の方法で共有


方法: 色の再マップ テーブルを使用する

再マップは、カラー リマップ テーブルに従ってイメージ内の色を変換するプロセスです。 色の再マップ テーブルは、 ColorMap オブジェクトの配列です。 配列内の各 ColorMap オブジェクトには、 OldColor プロパティと NewColor プロパティがあります。

GDI+ でイメージを描画すると、イメージの各ピクセルが古い色の配列と比較されます。 ピクセルの色が古い色と一致する場合、その色は対応する新しい色に変更されます。 色はレンダリングのためだけに変更されます。イメージ自体 ( Image または Bitmap オブジェクトに格納されている) の色の値は変更されません。

再マップされたイメージを描画するには、 ColorMap オブジェクトの配列を初期化します。 その配列をSetRemapTable オブジェクトのImageAttributes メソッドに渡し、ImageAttributes オブジェクトをDrawImage オブジェクトのGraphics メソッドに渡します。

次の例では、ファイル RemapInput.bmpから Image オブジェクトを作成します。 このコードでは、1 つの ColorMap オブジェクトで構成される色の再マップ テーブルが作成されます。 OldColor オブジェクトのColorRemapプロパティは赤で、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 フォームで使用できるように設計されており、PaintEventArgs イベント ハンドラーのパラメーターである ePaintが必要です。

こちらも参照ください