如何在图像上引入叠加层

时间:2011-10-26 03:26:18

标签: c# image image-processing

如何操作图像以添加半透明的1x1格式叠加层,就像C#中的第二张图像一样?

enter image description here enter image description here

2 个答案:

答案 0 :(得分:2)

将原始图像加载到system.Drawing.Image中,然后从中创建图形对象。加载要绘制的检查器图案的第二个图像,并使用您创建的图形对象重复在原始图像上绘制检查图像。

未经测试的示例

    Image Original;
    Image Overlay;

    Original = new Bitmap(100, 100, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //Load your real image here.
    Overlay = new Bitmap(2, 2 ,System.Drawing.Imaging.PixelFormat.Format32bppArgb);//Load your 2x2 (or whatever size you want) overlay image here.

    Graphics gr = Graphics.FromImage(Original);
    for (int y = 0; y < Original.Height + Overlay.Height; y = y + Overlay.Height)
    {
        for (int x = 0; x < Original.Width + OverlayWidth; x = x + Overlay.Width)
        {
            gr.DrawImage(Overlay, x, y);
        }  
    }
    gr.Dispose();

代码执行后,Original现在将包含应用了叠加层的原始图像。

答案 1 :(得分:2)

我能够修改我之前发布的答案并在代码中创建叠加层。创建叠加图像后,我使用TextureBrush填充原始图像的区域。下面代码中的设置创建了以下图像;您可以根据需要更改尺寸和颜色。

enter image description here enter image description here

// set the light and dark overlay colors
Color c1 = Color.FromArgb(80, Color.Silver);
Color c2 = Color.FromArgb(80, Color.DarkGray);

// set up the tile size - this will be 8x8 pixels, with each light/dark square being 4x4 pixels
int length = 8;
int halfLength = length / 2;

using (Bitmap overlay = new Bitmap(length, length, PixelFormat.Format32bppArgb))
{
    // draw the overlay - this will be a 2 x 2 grid of squares,
    // alternating between colors c1 and c2
    for (int x = 0; x < length; x++)
    {
        for (int y = 0; y < length; y++)
        {
            if ((x < halfLength && y < halfLength) || (x >= halfLength && y >= halfLength)) 
                overlay.SetPixel(x, y, c1);
            else 
                overlay.SetPixel(x, y, c2);
        }
    }

    // open the source image
    using (Image image = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\homers_brain.jpg"))
    using (Graphics graphics = Graphics.FromImage(image))
    {
        // create a brush from the overlay image, draw over the source image and save to a new image
        using (Brush overlayBrush = new TextureBrush(overlay))
        {
            graphics.FillRectangle(overlayBrush, new Rectangle(new Point(0, 0), image.Size));
            image.Save(@"C:\Users\Public\Pictures\Sample Pictures\homers_brain_overlay.jpg");
        }
    }
}