SoFunction
Updated on 2025-03-07

Complete example of generating C# (.net) watermark image

This article uses a complete example to describe the generation method of C# watermark images. It is a very practical technique. Share it for your reference.

The specific example code is as follows:

/*
 *
 * Instructions for use:
 * It is recommended to define a WaterImage instance first
 * Then use the attributes of the instance to match the parameters that need to be operated
 * Then define a WaterImageManage instance
 * Use the WaterImageManage instance to perform DrawImage() and print the image watermark
 * DrawWords() seal text watermark
 *
 */
using System;
using ;
using ;
using .Drawing2D;
using ;

namespace ABC
{

  /// <summary>
  /// Picture location  /// </summary>
  public enum ImagePosition
  {
    LeftTop,    //On top left    LeftBottom,  //Lower left    RightTop,    //Up to the right    RigthBottom, //Lower right    TopMiddle,   //Center the top    BottomMiddle, //The bottom center    Center      //center  }

  /// <summary>
  /// Operation and management of watermark pictures Design by Gary Gong From  /// </summary>
  public class WaterImageManage
  {
    /// <summary>
    /// Generate a new watermark image creation example    /// </summary>
    public WaterImageManage()
    {
      //
      // TODO: Add constructor logic here
      //
    }

    /// <summary>
    /// Add image watermark    /// </summary>
    /// <param name="sourcePicture">Source picture file name</param>    /// <param name="waterImage">Watermark image file name</param>    /// <param name="alpha">Transparency (the smaller the value 0.1-1.0, the higher the transparency)</param>    /// <param name="position">Position</param>    /// <param name="PicturePath" >PicturePath</param>    /// <returns>Returns the watermark file name generated in the specified folder</returns>    public string DrawImage(string sourcePicture,
                     string waterImage,
                     float alpha,

                     ImagePosition position,
                     string PicturePath)
    {
      //
      // Determine whether the parameters are valid      //
      if (sourcePicture ==  || waterImage ==  || alpha == 0.0 || PicturePath == )
      {
        return sourcePicture;
      }

      //
      // Source image, full path of watermark image      //
      string sourcePictureName = PicturePath + sourcePicture;
      string waterPictureName = PicturePath + waterImage;
      string fileSourceExtension = (sourcePictureName).ToLower();
      string fileWaterExtension = (waterPictureName).ToLower();
      //
      // Determine whether the file exists and whether the type is correct      //
      if ((sourcePictureName) == false ||
        (waterPictureName) == false || (
        fileSourceExtension != ".gif" &amp;&amp;
        fileSourceExtension != ".jpg" &amp;&amp;
        fileSourceExtension != ".png") || (
        fileWaterExtension != ".gif" &amp;&amp;
        fileWaterExtension != ".jpg" &amp;&amp;
        fileWaterExtension != ".png")
        )
      {
        return sourcePicture;
      }

      //

      // Target image name and full path      //
      string targetImage = ((sourcePictureName), "") + "_1101.jpg";

      //
      // Load the image that needs to be watermarked into the Image object      //
      Image imgPhoto = (sourcePictureName);
      //
      // Determine its length and width      //
      int phWidth = ;
      int phHeight = ;

      //
      // Encapsulates a GDI+ bitmap, which consists of pixel data of the graphic image and its properties.      //
      Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

      //
      // Set resolution      // 
      (, );

      //
      // Define a drawing screen to load bitmap      //
      Graphics grPhoto = (bmPhoto);

      //
      //Similarly, since the watermark is an image, we also need to define an Image to load it      //
      Image imgWatermark = new Bitmap(waterPictureName);

      //
      // Get the height and width of the watermark image      //
      int wmWidth = ;
      int wmHeight = ;

      //SmoothingMode: Specifies whether smoothing (unaliasing) is applied to the edges of straight lines, curves, and filled areas.      // Member Name Description      // AntiAlias ​​Specifies the rendering of unaliased.      // Default specifies that no aliasing is removed.
      // HighQuality specifies high-quality, low-speed rendering.      // HighSpeed ​​specifies high speed, low quality presentation.      // Invalid Specifies an invalid mode.      // None specifies that no aliasing is removed.       = ;

 

      //
      // For the first time, depict our base map on the drawing screen      //
      (imgPhoto,
                    new Rectangle(0, 0, phWidth, phHeight),
                    0,
                    0,
                    phWidth,
                    phHeight,
                    );

      //
      // Like the base map, we need a bitmap to load the watermark image.  and set its resolution      //
      Bitmap bmWatermark = new Bitmap(bmPhoto);
      (, );

      //
      // Continue, load the watermark image into a drawing screen grWatermark      //
      Graphics grWatermark = (bmWatermark);

      //
      //The ImageAttributes object contains information about how to manipulate the bitmap and metafile colors when rendering.      //   

      ImageAttributes imageAttributes = new ImageAttributes();

      //
      //Colormap: Define the mapping of converted colors      //
      ColorMap colorMap = new ColorMap();

      //
      //My watermark image is defined as a picture with a green background color is replaced with transparent      //
       = (255, 0, 255, 0);
       = (0, 0, 0, 0);

      ColorMap[] remapTable = { colorMap };

      (remapTable, );

      float[][] colorMatrixElements = { 
      new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // red red      new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, //green green      new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, //blue blue      new float[] {0.0f, 0.0f, 0.0f, alpha, 0.0f}, //transparency      new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};//

      // ColorMatrix: Defines a 5 x 5 matrix containing RGBA spatial coordinates.      // Several methods of the ImageAttributes class adjust the image color by using the color matrix.      ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);


      (wmColorMatrix, ,
       );

      //
      //After setting the color above, start setting the position below      //
      int xPosOfWm;
      int yPosOfWm;

      switch (position)
      {
        case :
          xPosOfWm = (phWidth - wmWidth) / 2;
          yPosOfWm = phHeight - wmHeight - 10;
          break;

        case :
          xPosOfWm = (phWidth - wmWidth) / 2;
          yPosOfWm = (phHeight - wmHeight) / 2;
          break;
        case :
          xPosOfWm = 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case :
          xPosOfWm = 10;
          yPosOfWm = 10;
          break;
        case :
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = 10;
          break;
        case :
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case :
          xPosOfWm = (phWidth - wmWidth) / 2;
          yPosOfWm = 10;
          break;
        default:
          xPosOfWm = 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
      }

      // For the second drawing, print the watermark on it      //
      (imgWatermark,
       new Rectangle(xPosOfWm,
                 yPosOfWm,
                 wmWidth,
                 wmHeight),
                 0,
                 0,
                 wmWidth,
                 wmHeight,
                 ,
                 imageAttributes);

      imgPhoto = bmWatermark;
      ();
      ();

      //
      // Save the file to the server folder      //
      (targetImage, );
      ();
      ();
      return (PicturePath, "");
    }

/*
 *
 * Instructions for use:
 * It is recommended to define a WaterImage instance first
 * Then use the attributes of the instance to match the parameters that need to be operated
 * Then define a WaterImageManage instance
 * Use the WaterImageManage instance to perform DrawImage() and print the image watermark
 * DrawWords() seal text watermark
 *
 -*/

    /// &lt;summary&gt;
    /// Add watermark text to the picture    /// &lt;/summary&gt;
    /// <param name="sourcePicture">Source picture file (file name, not including path)</param>
    /// <param name="waterWords">Texts that need to be added to the picture</param>    /// <param name="alpha">Transparency</param>    /// <param name="position">Position</param>    /// <param name="PicturePath">File Path</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public string DrawWords(string sourcePicture,
                     string waterWords,
                     float alpha,
                     ImagePosition position,
                     string PicturePath)
    {
      //
      // Determine whether the parameters are valid      //
      if (sourcePicture ==  || waterWords ==  || alpha == 0.0 || PicturePath == )
      {
        return sourcePicture;
      }

      //
      // Full path of source image      //
      if (( - 1, 1) != "/")
        PicturePath += "/";
      string sourcePictureName = PicturePath + sourcePicture;
      string fileExtension = (sourcePictureName).ToLower();

      //
      // Determine whether the file exists and whether the file name is correct      //
      if ((sourcePictureName) == false || (
        fileExtension != ".gif" &amp;&amp;
        fileExtension != ".jpg" &amp;&amp;

        fileExtension != ".png"))
      {
        return sourcePicture;
      }

      //
      // Target image name and full path      //
      string targetImage = ((sourcePictureName), "") + "_0703.jpg";

      //Create an image object to load the image to be added with a watermark      Image imgPhoto = (sourcePictureName);

      //Get the width and height of the picture      int phWidth = ;
      int phHeight = ;

      //
      //Create a bitmap, the same size as the image we need to add a watermark      Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

      //SetResolution: Set the resolution of this Bitmap      //Here we directly assign the resolution of the image we need to add watermark to bitmap      (, );

      //Graphics: Encapsulate a GDI+ drawing surface.      Graphics grPhoto = (bmPhoto);

      //Set the quality of the graphics       = ;

      //Draw (copy) the image we want to add watermark into the figure according to its original size      (
       imgPhoto,                      // Image to add watermark       new Rectangle(0, 0, phWidth, phHeight), // According to the width and height of the watermark image to be added       0,                           // The X direction starts from point 0       0,                           // Direction Y
       phWidth,                      // X-direction drawing length       phHeight,                      // Y direction description length       );               // The unit of the depiction is pixels used here
      //We will determine the size of the added text based on the size of the picture      //Here we define an array to determine      int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

      //Font      Font crFont = null;
      //The width and height of the rectangle, SizeF has three properties, namely Height height, width width, and whether IsEmpty is empty      SizeF crSize = new SizeF();

      //Use a loop statement to select the model we want to add text      // Until its length is smaller than the width of the picture      for (int i = 0; i &lt; 7; i++)
      {
        crFont = new Font("arial", sizes[i], );

        //Measure the specified string drawn with the specified Font object and formatted with the specified StringFormat object.        crSize = (waterWords, crFont);

        // The ushort keyword represents an integer data type        if ((ushort) &lt; (ushort)phWidth)
          break;
      }

      //The distance of the cut edge is 5%, define the text display (because the height and width of different pictures are displayed differently, so cut by percentage)      int yPixlesFromBottom = (int)(phHeight * .05);

      //Define the position of the text on the picture      float wmHeight = ;
      float wmWidth = ;

      float xPosOfWm;

      float yPosOfWm;

   switch (position)
      {
        case :
          xPosOfWm = phWidth / 2;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case :
          xPosOfWm = phWidth / 2;
          yPosOfWm = phHeight / 2;
          break;
        case :
          xPosOfWm = wmWidth;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case :
          xPosOfWm = wmWidth / 2;
          yPosOfWm = wmHeight / 2;
          break;
        case :
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = wmHeight;
          break;
        case :
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case :
          xPosOfWm = phWidth / 2;
          yPosOfWm = wmWidth;

          break;
        default:
          xPosOfWm = wmWidth;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
      }

      //Encapsulate text layout information (such as alignment, text orientation, and Tab docks), display operations (such as ellipsis insertion and national standard (National) digital replacement) and OpenType functions.      StringFormat StrFormat = new StringFormat();

      //Define the text to be printed in the center and align in the center       = ;

      //SolidBrush: Define monochrome brushes.  Brushes are used to fill shapes such as rectangles, ellipses, sectors, polygons, and closed paths.      //This brush is a paintbrush that depicts shadows and is gray      int m_alpha = Convert.ToInt32(256 * alpha);
      SolidBrush semiTransBrush2 = new SolidBrush((m_alpha, 0, 0, 0));

      //Describe text information, this layer is offset by one pixel to the right and down to indicate the shadow effect      //DrawString draws the specified text string in the specified rectangle and uses the specified Brush and Font objects.      (waterWords,                  //string of text
                    crFont,                     //font
                    semiTransBrush2,              //Brush
                    new PointF(xPosOfWm + 1, yPosOfWm + 1), //Position
                    StrFormat);

      //Create a Color structure from four ARGB components (alpha, red, green and blue) values, set the transparency to 153 here      //This brush is a brush that depicts formal text and is white      SolidBrush semiTransBrush = new SolidBrush((153, 255, 255, 255));

      //The second time I draw this figure is based on the first description      (waterWords,         //string of text
                    crFont,                  //font
                    semiTransBrush,              //Brush
                    new PointF(xPosOfWm, yPosOfWm), //Position
                    StrFormat);

      //imgPhoto is the Image object we created to load the final graphics      //bmPhoto is the container we use to make graphics, which is a Bitmap object      imgPhoto = bmPhoto;
      //Release resources and release the defined Graphics instance grPhoto, grPhoto has fulfilled merits      ();

      //Save grPhoto      (targetImage, );
      ();

      return (PicturePath, "");
    }
  }

  /// &lt;summary&gt;
  /// Information about loading watermark pictures  /// &lt;/summary&gt;
  public class WaterImage
  {
    public WaterImage()
    {

    }

    private string m_sourcePicture;
    /// &lt;summary&gt;
    /// Source image address name (with suffix)
    /// &lt;/summary&gt;
    public string SourcePicture
    {
      get { return m_sourcePicture; }
      set { m_sourcePicture = value; }
    }

    private string m_waterImager;
    /// &lt;summary&gt;
    /// Watermark image name (with suffix)    /// &lt;/summary&gt;
    public string WaterPicture
    {
      get { return m_waterImager; }
      set { m_waterImager = value; }
    }

    private float m_alpha;
    /// &lt;summary&gt;
    /// Transparency of text in watermark image    /// &lt;/summary&gt;
    public float Alpha
    {
      get { return m_alpha; }
      set { m_alpha = value; }
    }

    private ImagePosition m_postition;
    /// &lt;summary&gt;
    /// The location of the watermark picture or text in the picture    /// &lt;/summary&gt;
    public ImagePosition Position
    {
      get { return m_postition; }
      set { m_postition = value; }
    }

    private string m_words;
    /// &lt;summary&gt;
    /// Content of watermark text    /// &lt;/summary&gt;
    public string Words
    {
      get { return m_words; }
      set { m_words = value; }
    }

  }
}

I believe that the description in this article will have a certain reference and reference effect for everyone's C# programming.