开发者

Replace colors in indexed image using C#

I'm using Graphics.DrawImage to write a index bitmap into another image. The color black in the indexed image should be replaced with a transparent color when written to the "targetBitmap"

How do I do this in a nice performant way ?

var graphics = Graphics.FromImage(targetBitmap);

//I want the black color in "indexBitmap" to be transparent when it's written to "targetBit开发者_如何学Gomap"
graphics.DrawImage(indexedBitmap,...)


Creating a color map and passing it as an "ImageAttributes" argument to DrawImage worked for me

var colorMaps = new[]{
   new ColorMap {OldColor = Color.FromArgb(255, 0, 0, 0), NewColor =  Color.Transparent}
};

var attr = new ImageAttributes();
attr.SetRemapTable(colorMaps);


How about using SetColorKey?


SetColorKey allows you to choose a transparent background when drawing the image on a graphics object. But the fact is that this doesn't work when the SetRemapTable() function has been called.

You can make that work also by adding an extra ColorMap in the "colorMaps" array. This extra ColorMap should have - OldColor = 'Choose the transparent color' - NewColor = Color.Transparent and then call the SetRemapTable with the extended sub.

Below you see a code sample in C# to easily draw an image to a graphics object. I use this to make a game with graphics. This void (sub in basic) allows you to draw an image to graphics (eg. FormX.CreateGraphics()).

You can replace certain colors by other colors, and also choose a transparent color.

You can also draw the image with a specified angle (degrees).

public static void DrawImageToGraphics(Graphics gr, Bitmap img, Rectangle DestRect, Color[] OldColors, Color[] NewColors, Color TransparantColor, uint Angle)
{
    System.Drawing.Drawing2D.Matrix lmx = new System.Drawing.Drawing2D.Matrix();
    lmx.RotateAt(Angle, new PointF((DestRect.Left + DestRect.Right) / 2, (DestRect.Top + DestRect.Bottom) / 2));
    gr.Transform = lmx;

    System.Drawing.Imaging.ColorMap[] maps = new System.Drawing.Imaging.ColorMap[OldColors.Count() + 1];
    for (int i = 0; i < OldColors.Count(); i++)
    {
        maps[i].OldColor = OldColors[i];
        maps[i].NewColor = NewColors[i];
    }
    maps[OldColors.Count()].OldColor = TransparantColor;
    maps[OldColors.Count()].NewColor = Color.Transparent;
    System.Drawing.Imaging.ImageAttributes attr = new System.Drawing.Imaging.ImageAttributes();
    attr.SetRemapTable(maps);

    gr.DrawImage(img, DestRect, 0, 0, img.Width, img.Height, GraphicsUnit.Point, attr);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜