2009-08-03 70 views
17

如何将水印图像添​​加到其他图像上?将水印图像放在其他图像上(C#,ASP.Net)

我可以将文字放在图像上作为水印,但是现在我有一张图像,我想放在那里而不是文本。我如何在C#中执行此操作?

再来一次具体,我有图像X,我想用它作为水印符号。我希望这个符号出现在我的网站上显示的所有图像上。因此,我将有图像X水印图像Y和Z.

下面的代码我现在有创建水印:

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); 
     } 
+0

从你上面的代码另一种解决方案,它与GIF格式图片的问题。 – 2009-09-16 04:05:33

+0

你,我不担心GIF。我所有的图片都是JPG格式,水印是PNG,所以我只是忽略了这些。 – Miles 2009-09-19 16:01:31

回答

11
在调用gr.DrawString同一个地方

,你也可以做gr.DrawImage(position,size,overlayImage)。如果从PNG文件(透明度)加载图像到覆盖图以产生最佳质量,它会有所帮助。