20

如何将水印图像添​​加到其他图像上?

我可以在图像上放置文本作为水印,但现在我有一个图像,我想放在那里而不是文本。我如何在 C# 中做到这一点?

再说一次,我有图像 X,我想用它作为水印符号。我希望这个符号在我的网站上显示时出现在我的所有图像上。所以我将在图像 Y 和 Z 上添加图像 X 水印。

这是我目前拥有的创建水印的代码:

public static void AddWaterMark(MemoryStream ms, string watermarkText, MemoryStream outputStream)
        {
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            Graphics gr = Graphics.FromImage(img);
            Font font = new Font("Tahoma", (float)40);
            Color color = Color.FromArgb(50, 241, 235, 105);
            double tangent = (double)img.Height / (double)img.Width;
            double angle = Math.Atan(tangent) * (180 / Math.PI);
            double halfHypotenuse = Math.Sqrt((img.Height * img.Height) + (img.Width * img.Width)) / 2;
            double sin, cos, opp1, adj1, opp2, adj2;

            for (int i = 100; i > 0; i--)
            {
                font = new Font("Tahoma", i, FontStyle.Bold);
                SizeF sizef = gr.MeasureString(watermarkText, font, int.MaxValue);

                sin = Math.Sin(angle * (Math.PI / 180));
                cos = Math.Cos(angle * (Math.PI / 180));
                opp1 = sin * sizef.Width;
                adj1 = cos * sizef.Height;
                opp2 = sin * sizef.Height;
                adj2 = cos * sizef.Width;

                if (opp1 + adj1 < img.Height && opp2 + adj2 < img.Width)
                    break;
                //
            }

            StringFormat stringFormat = new StringFormat();
            stringFormat.Alignment = StringAlignment.Center;
            stringFormat.LineAlignment = StringAlignment.Center;

            gr.SmoothingMode = SmoothingMode.AntiAlias;
            gr.RotateTransform((float)angle);
            gr.DrawString(watermarkText, font, new SolidBrush(color), new Point((int)halfHypotenuse, 0), stringFormat);

            img.Save(outputStream, ImageFormat.Jpeg);
        }
4

2 回答 2

13

在你调用 gr.DrawString 的同一个地方,你也可以做 gr.DrawImage(position, size, overlayImage)。如果您的图像叠加层是从 PNG 文件(具有透明度)加载以产生最佳质量,这将有所帮助。

于 2009-08-03T21:18:58.233 回答
5

这是另一个使用 GDI+ 的解决方案

使用 GDI+ for .NET 创建带水印的照片

于 2011-02-24T08:39:36.287 回答