【问题标题】:Replace colors in indexed image using C#使用 C# 替换索引图像中的颜色
【发布时间】:2011-07-19 12:39:02
【问题描述】:

我正在使用 Graphics.DrawImage 将索引位图写入另一个图像。写入“targetBitmap”时,索引图像中的黑色应替换为透明色

我如何以一种高效的方式做到这一点?

var graphics = Graphics.FromImage(targetBitmap);

//I want the black color in "indexBitmap" to be transparent when it's written to "targetBitmap"
graphics.DrawImage(indexedBitmap,...)

【问题讨论】:

    标签: c# graphics gdi+


    【解决方案1】:

    创建一个颜色映射并将其作为“ImageAttributes”参数传递给 DrawImage 对我有用

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

    【讨论】:

      【解决方案2】:

      SetColorKey怎么样?

      【讨论】:

        【解决方案3】:

        SetColorKey 允许您在图形对象上绘制图像时选择透明背景。 但事实是,当调用 SetRemapTable() 函数时,这不起作用。

        您也可以通过在“colorMaps”数组中添加一个额外的 ColorMap 来实现这一点。 这个额外的 ColorMap 应该有 - OldColor = '选择透明色' - NewColor = 颜色.透明 然后使用扩展子调用 SetRemapTable。

        下面是一个 C# 代码示例,可以轻松地将图像绘制到图形对象。 我用它来制作带有图形的游戏。 这个 void(基本的 sub)允许您将图像绘制到图形(例如 FormX.CreateGraphics())。

        您可以将某些颜色替换为其他颜色,也可以选择透明颜色。

        您还可以绘制指定角度(度)的图像。

        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);
        }
        

        【讨论】:

          猜你喜欢
          • 2012-04-09
          • 2016-02-07
          • 2016-01-25
          • 2018-05-11
          • 2010-12-05
          • 1970-01-01
          • 2016-06-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多