在其他图像上放置水印图像(C#、ASP.Net)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1224653/
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
Place watermark image on other images (C#, ASP.Net)
提问by Miles
How do I add a watermark image onto other images?
如何将水印图像添加到其他图像上?
I'm able to place text on an image as a water mark but now I have an image that I'd like to put on there instead of the text. How do I do this in C#?
我可以将文本作为水印放置在图像上,但现在我有一个图像,我想放在那里而不是文本。我如何在 C# 中做到这一点?
Just one more time to be specific, I have image X and I want to use it as a watermark symbol. I want this symbol to appear on all my image when shown on my website. So I will have image X watermarked on image Y and Z.
再具体一点,我有图像 X,我想将其用作水印符号。我希望这个符号在我的网站上显示时出现在我的所有图像上。所以我将在图像 Y 和 Z 上添加图像 X 水印。
Here's the code I currently have that creates the watermark:
这是我目前创建水印的代码:
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);
}
采纳答案by Miles
in the same place where you call gr.DrawString, you can also do gr.DrawImage(position, size, overlayImage). It helps if your image-to-overlay is loaded from a PNG file (with transparency) to produce the best quality.
在你调用 gr.DrawString 的同一个地方,你也可以做 gr.DrawImage(position, size, overlayImage)。如果从 PNG 文件(具有透明度)加载图像到叠加层以产生最佳质量,它会有所帮助。
回答by HasanG
Here is another solution which uses GDI+
这是另一个使用 GDI+ 的解决方案