【问题标题】:How can I introduce an overlay on an image如何在图像上引入叠加层
【发布时间】:2011-10-26 03:26:18
【问题描述】:

如何操作图像以添加半透明的 1x1 检查覆盖,就像 C# 中的第二个图像一样?

【问题讨论】:

  • 取决于。例如,您是想加载图像、修改它并重新保存它,还是保存一个全新的图像,或者只为您的 UI 做一些事情。我们真的需要更多信息。
  • 我想创建一个新图像并将其上传到 Amazon S3。有什么区别?
  • 这个answer 可能会有所帮助 - 使用 2x2 覆盖纹理画笔。
  • 如果您只想对图像进行一些效果,您的答案取决于您的平台是什么(asp.net、silverlight 等)。听起来您可能想研究 GDI+

标签: c# image image-processing


【解决方案1】:

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

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

【讨论】:

    【解决方案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 现在将包含应用了叠加层的原始图像。

    【讨论】:

    • 它的书写方式可能不会覆盖左下边缘的几个像素。我将把 Overlay 大小添加到循环边界以纠正它。我还切换了一个变量,现在也已修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 2021-11-23
    • 2014-12-16
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多