1

试图找出在 C# 中以特定颜色的掩码呈现图像的最优雅的方法(通过 System.Drawing 或在桌面和 ASP.NET 应用程序中都可以使用的等效方法)。

蒙版图像将包含应该“绘制”图像的绿色键。

(下面的预期结果图像并不完美,手套索......)

期望的结果

4

3 回答 3

3

为此有多种技术:

  1. 扫描像素数据并构建蒙版图像(如 itsme86 和 Moby Disk 已建议的那样)

  2. 一种扫描的变体,它从蒙版构建一个剪切区域并在绘图时使用它(请参阅Bob Powell的这篇文章)

  3. Graphics.DrawImage在通话中使用颜色键进行屏蔽。

我将专注于第三个选项。

假设您要从掩码中消除的图像颜色是Color.Lime,我们可以ImageAttributes.SetColorKey在这样的调用期间停止绘制任何该颜色Graphics.DrawImage

using (Image background = Bitmap.FromFile("tree.png"))
using (Image masksource = Bitmap.FromFile("mask.png"))
using (var imgattr = new ImageAttributes())
{
    // set color key to Lime 
    imgattr.SetColorKey(Color.Lime, Color.Lime);

    // Draw non-lime portions of mask onto original
    using (var g = Graphics.FromImage(background))
    {
        g.DrawImage(
            masksource,
            new Rectangle(0, 0, masksource.Width, masksource.Height),
            0, 0, masksource.Width, masksource.Height,
            GraphicsUnit.Pixel, imgattr
        );
    }

    // Do something with the composited image here...
    background.Save("Composited.png");
}

结果: 结果

Color.Fuchsia如果您想将树的这些位放入另一个图像中,您可以使用相同的技术(使用颜色键)。

于 2014-01-22T23:53:37.523 回答
2

你想要这样的东西:

Bitmap original = new Bitmap(@"tree.jpg");
Bitmap mask = new Bitmap(@"mask.jpg");

int width = original.Width;
int height = original.Height;

// This is the color that will be replaced in the mask
Color key = Color.FromArgb(0,255,0);

// Processing one pixel at a time is slow, but easy to understand
for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        // Is this pixel "green" ?
        if (mask.GetPixel(x,y) == key)
        {
            // Copy the pixel color from the original
            Color c = original.GetPixel(x,y);

            // Into the mask
            mask.SetPixel(x,y,c);
        }
    }
}
于 2014-01-22T22:38:12.307 回答
0

您可能会读入掩码并将其转换为图像,当像素为绿色时,alpha 通道设置为 0,当像素为任何其他颜色时,alpha 通道设置为 0xFF。然后您可以在原始图像上绘制蒙版图像。

于 2014-01-22T22:17:47.190 回答