C# 为图像添加图层

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/637801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:16:25  来源:igfitidea点击:

C# add a layer to an image

c#image

提问by

I would like to add a layer to an image with the logo of the company.

我想为带有公司徽标的图像添加一个图层。

The logo should be placed on the center of the image (little opacity).

徽标应放置在图像的中心(不透明)。

How can I do that?

我怎样才能做到这一点?

回答by REA_ANDREW

Here is one I made earlier which creates a new badge for some images:

这是我之前制作的一个,它为一些图像创建了一个新的徽章:

EDIT, I designed the function which I supply a maxWidth and a maxHeight, it resizes without distortion.

编辑,我设计了提供 maxWidth 和 maxHeight 的函数,它可以在不失真的情况下调整大小。

Requirements:

要求:

using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

The Code

编码

    using (Image i = Image.FromFile(HttpContext.Current.Server.MapPath(fileName)))
    {
        float imageWidth = i.PhysicalDimension.Width;
        float imageHeight = i.PhysicalDimension.Height;
        float percentage = maxWidth / imageWidth;
        float newWidth = imageWidth * percentage;
        float newHeight = imageHeight * percentage;

        if (newHeight > maxHeight)
        {
            percentage = maxHeight / newHeight;

            newWidth = newWidth * percentage;
            newHeight = newHeight * percentage;
        }

        using (Bitmap b = new Bitmap((int)newWidth, (int)newHeight))
        {
            using (Graphics g = Graphics.FromImage(b))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                g.DrawImage(i, new Rectangle(0, 0, b.Width, b.Height));

                if (effect == "new")
                {
                    using (Image j = Image.FromFile(HttpContext.Current.Server.MapPath("/ImageEffects/") + "new.png", true))
                    {
                        g.DrawImage(j, new Rectangle(0, 0, 60, 60));

                    }
                }

                Image newImage = Image.FromHbitmap(b.GetHbitmap());

                return newImage;
            }
        }

    }
}