2009-08-03 9 views
17

Comment ajouter une image de filigrane sur d'autres images?Placer une image de filigrane sur d'autres images (C#, ASP.Net)

Je suis capable de placer du texte sur une image comme une marque d'eau mais maintenant j'ai une image que je voudrais mettre là-bas au lieu du texte. Comment est-ce que je fais cela en C#?

Juste une fois de plus pour être précis, j'ai l'image X et je veux l'utiliser comme un symbole de filigrane. Je veux que ce symbole apparaisse sur toute mon image lorsqu'il est affiché sur mon site Web. Je vais donc l'image X filigrané sur l'image Y et Z.

Voici le code que j'ai actuellement qui crée le filigrane:

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

À partir de votre code ci-dessus, il a un problème avec le format gif photo. –

+0

ya, je ne me suis pas inquiété avec les GIF. Toutes mes photos sont en format JPG et la marque d'eau est un PNG, donc je les ai simplement ignorés. – Miles

Répondre

11

au même endroit où vous appelez gr.DrawString, vous pouvez également faire gr.DrawImage (position, taille, overlayImage). Cela aide si votre image à superposer est chargé à partir d'un fichier PNG (avec transparence) pour produire la meilleure qualité.

+1

ahhhhh je me sens comme un crétin maintenant ... hahaha, merci – Miles

Questions connexes