C ES1en. net watermark image generation complete example

  • 2020-11-03 22:34:46
  • OfStack

In this paper, a complete example is given to illustrate the generation method of C# watermark image. It's a very practical skill. Share to everybody for everybody reference.

The concrete example code is as follows:


/*
* 
*   Instructions for use: 
*  It is recommended to first define 1 a WaterImage The instance 
*  Then use the properties of the instance to match the parameters that need to be manipulated 
*  And then define the 1 a WaterImageManage The instance 
*  using WaterImageManage instance DrawImage (), printing image watermark 
*  DrawWords () Printed text watermark 
* 
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace ABC
{

  /// <summary>
  ///  Image location 
  /// </summary>
  public enum ImagePosition
  {
    LeftTop,    // Upper left 
    LeftBottom,  // The lower left 
    RightTop,    // The upper right 
    RigthBottom, // The lower right 
    TopMiddle,   // At the top of the center 
    BottomMiddle, // At the bottom of the center 
    Center      // center 
  }

  /// <summary>
  ///  Watermark image operation management  Design by Gary Gong From Demetersoft.com
  /// </summary>
  public class WaterImageManage
  {
    /// <summary>
    ///  generate 1 A new watermark image production example 
    /// </summary>
    public WaterImageManage()
    {
      //
      // TODO: Add constructor logic here
      //
    }

    /// <summary>
    ///  Add image watermark 
    /// </summary>
    /// <param name="sourcePicture"> Source image file name </param>
    /// <param name="waterImage"> File name of watermark image </param>
    /// <param name="alpha"> transparency (0.1-1.0 The smaller the value, the more transparent it is )</param>
    /// <param name="position"> location </param>
    /// <param name="PicturePath" > Path of the picture </param>
    /// <returns> Returns the watermark filename generated under the specified folder </returns>
    public string DrawImage(string sourcePicture,
                     string waterImage,
                     float alpha,

                     ImagePosition position,
                     string PicturePath)
    {
      //
      //  Determine if the parameter is valid 
      //
      if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0 || PicturePath == string.Empty)
      {
        return sourcePicture;
      }

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

      //

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

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

      //
      //  encapsulation  GDI+  A bitmap consisting of pixel data of a graphic image and its attributes. 
      //
      Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

      //
      //  Set resolution 
      // 
      bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

      //
      //  define 1 A drawing screen is used to load bitmaps 
      //
      Graphics grPhoto = Graphics.FromImage(bmPhoto);

      //
      // Also, since a watermark is an image, we need to define it 1 a Image To load it 
      //
      Image imgWatermark = new Bitmap(waterPictureName);

      //
      //  Gets the height and width of the watermark image 
      //
      int wmWidth = imgWatermark.Width;
      int wmHeight = imgWatermark.Height;

      //SmoothingMode : Specifies whether smoothing (anti-aliasing) is applied to the edges of lines, curves, and filled areas. 
      //  Member name    instructions  
      // AntiAlias    Specifies the render of the anti-aliasing.  
      // Default     Specifies that the sawtooth is not eliminated. 

      // HighQuality  Specifies high quality, low speed rendering.  
      // HighSpeed   Specifies high speed, low quality rendering.  
      // Invalid     The specified 1 Invalid mode.  
      // None      Specifies that the sawtooth is not eliminated.  
      grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

 

      //
      //  The first 1 Subsketch, to represent our base image on a drawing 
      //
      grPhoto.DrawImage(imgPhoto,
                    new Rectangle(0, 0, phWidth, phHeight),
                    0,
                    0,
                    phWidth,
                    phHeight,
                    GraphicsUnit.Pixel);

      //
      //  And reproduction 1 Yes, we do 1 Bitmap to load watermark image. And set its resolution 
      //
      Bitmap bmWatermark = new Bitmap(bmPhoto);
      bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

      //
      //  Go ahead and load the watermark image into 1 A drawing screen grWatermark
      //
      Graphics grWatermark = Graphics.FromImage(bmWatermark);

      //
      //ImageAttributes  Object contains information about how to manipulate bitmaps and metafile colors during rendering. 
      //   

      ImageAttributes imageAttributes = new ImageAttributes();

      //
      //Colormap:  Defines a mapping to transform colors 
      //
      ColorMap colorMap = new ColorMap();

      //
      // My watermark is defined as an image with a green background color that is replaced with transparency 
      //
      colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
      colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

      ColorMap[] remapTable = { colorMap };

      imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

      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: Definition contains  RGBA  Spatially coordinate  5 x 5  Matrix. 
      // ImageAttributes  Class by using a color matrix to adjust the color of an image. 
      ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);


      imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
       ColorAdjustType.Bitmap);

      //
      // After setting the color at the top, start setting the position at the bottom 
      //
      int xPosOfWm;
      int yPosOfWm;

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

        case ImagePosition.Center:
          xPosOfWm = (phWidth - wmWidth) / 2;
          yPosOfWm = (phHeight - wmHeight) / 2;
          break;
        case ImagePosition.LeftBottom:
          xPosOfWm = 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.LeftTop:
          xPosOfWm = 10;
          yPosOfWm = 10;
          break;
        case ImagePosition.RightTop:
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = 10;
          break;
        case ImagePosition.RigthBottom:
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.TopMiddle:
          xPosOfWm = (phWidth - wmWidth) / 2;
          yPosOfWm = 10;
          break;
        default:
          xPosOfWm = 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
      }

      //  The first 2 Second drawing, print the watermark 
      //
      grWatermark.DrawImage(imgWatermark,
       new Rectangle(xPosOfWm,
                 yPosOfWm,
                 wmWidth,
                 wmHeight),
                 0,
                 0,
                 wmWidth,
                 wmHeight,
                 GraphicsUnit.Pixel,
                 imageAttributes);

      imgPhoto = bmWatermark;
      grPhoto.Dispose();
      grWatermark.Dispose();

      //
      //  Save the file to a folder on the server 
      //
      imgPhoto.Save(targetImage, ImageFormat.Jpeg);
      imgPhoto.Dispose();
      imgWatermark.Dispose();
      return targetImage.Replace(PicturePath, "");
    }

/*
* 
*  Instructions for use: 
*  It is recommended to first define 1 a WaterImage The instance 
*  Then use the properties of the instance to match the parameters that need to be manipulated 
*  And then define the 1 a WaterImageManage The instance 
*  using WaterImageManage instance DrawImage (), printing image watermark 
*  DrawWords () Printed text watermark 
* 
-*/

    /// <summary>
    ///  Add watermark text to the image 
    /// </summary>
    /// <param name="sourcePicture"> Source image file ( File name, not including path )</param>

    /// <param name="waterWords"> Text that needs to be added to the image </param>
    /// <param name="alpha"> transparency </param>
    /// <param name="position"> location </param>
    /// <param name="PicturePath"> The file path </param>
    /// <returns></returns>
    public string DrawWords(string sourcePicture,
                     string waterWords,
                     float alpha,
                     ImagePosition position,
                     string PicturePath)
    {
      //
      //  Determine if the parameter is valid 
      //
      if (sourcePicture == string.Empty || waterWords == string.Empty || alpha == 0.0 || PicturePath == string.Empty)
      {
        return sourcePicture;
      }

      //
      //  Full path to source image 
      //
      if (PicturePath.Substring(PicturePath.Length - 1, 1) != "/")
        PicturePath += "/";
      string sourcePictureName = PicturePath + sourcePicture;
      string fileExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();

      //
      //  Determine if the file exists , And whether the file name is correct 
      //
      if (System.IO.File.Exists(sourcePictureName) == false || (
        fileExtension != ".gif" &&
        fileExtension != ".jpg" &&

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

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

      // create 1 The image object is used to load the image to be watermarked 
      Image imgPhoto = Image.FromFile(sourcePictureName);

      // Gets the width and height of the image 
      int phWidth = imgPhoto.Width;
      int phHeight = imgPhoto.Height;

      //
      // To establish 1 a bitmap , and the image we need to watermark 1 The sample size 
      Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

      //SetResolution : set this  Bitmap  The resolution of the 
      // Here we directly assign the resolution of the image we need to add the watermark to bitmap
      bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

      //Graphics : encapsulation 1 a  GDI+  Drawing surface. 
      Graphics grPhoto = Graphics.FromImage(bmPhoto);

      // Set the quality of the graphics 
      grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

      // Draw (copy) the original size of the image to which we want to add the watermark into the graph 
      grPhoto.DrawImage(
       imgPhoto,                      //   The image to be watermarked 
       new Rectangle(0, 0, phWidth, phHeight), //  Depending on the width and height of the watermark image to be added 
       0,                           // X Direction from the 0 Point start drawing 
       0,                           // Y The direction of 

       phWidth,                      // X Direction drawing length 
       phHeight,                      // Y Direction drawing length 
       GraphicsUnit.Pixel);               //  The units of drawing, in this case pixels 

      // According to the size of the image we determine the size of the text added 
      // Here we define it 1 An array to determine 
      int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

      // The font 
      Font crFont = null;
      // The width and height of the rectangle, SizeF There are 3 Are, respectively Height High, width Wide, IsEmpty Whether is empty 
      SizeF crSize = new SizeF();

      // using 1 To select the type of text we want to add 
      // Until its length is smaller than the width of the image 
      for (int i = 0; i < 7; i++)
      {
        crFont = new Font("arial", sizes[i], FontStyle.Bold);

        // Specified for measurement  Font  Object drawn and specified  StringFormat  Object to format a specified string. 
        crSize = grPhoto.MeasureString(waterWords, crFont);

        // ushort  Keyword representation 1 Various integer data types 
        if ((ushort)crSize.Width < (ushort)phWidth)
          break;
      }

      // Cutting edge 5% The distance of the definition text is displayed ( Because different images show different heights and widths, cut them by percentage )
      int yPixlesFromBottom = (int)(phHeight * .05);

      // Defines the position of text on an image 
      float wmHeight = crSize.Height;
      float wmWidth = crSize.Width;

      float xPosOfWm;

      float yPosOfWm;

   switch (position)
      {
        case ImagePosition.BottomMiddle:
          xPosOfWm = phWidth / 2;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.Center:
          xPosOfWm = phWidth / 2;
          yPosOfWm = phHeight / 2;
          break;
        case ImagePosition.LeftBottom:
          xPosOfWm = wmWidth;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.LeftTop:
          xPosOfWm = wmWidth / 2;
          yPosOfWm = wmHeight / 2;
          break;
        case ImagePosition.RightTop:
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = wmHeight;
          break;
        case ImagePosition.RigthBottom:
          xPosOfWm = phWidth - wmWidth - 10;
          yPosOfWm = phHeight - wmHeight - 10;
          break;
        case ImagePosition.TopMiddle:
          xPosOfWm = phWidth / 2;
          yPosOfWm = wmWidth;

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

      // Encapsulates text layout information such as alignment, text orientation, and  Tab  Parking Spaces), display operations (such as ellipsis insertion and national standards  (National)  Numeric substitution) and  OpenType  Function. 
      StringFormat StrFormat = new StringFormat();

      // Defines the text that needs to be printed centered 
      StrFormat.Alignment = StringAlignment.Center;

      //SolidBrush: Define a monochrome brush. The brush is used to fill in graphic shapes such as rectangles, ellipses, sectors, polygons, and closed paths. 
      // This brush is a shadow brush and is grey 
      int m_alpha = Convert.ToInt32(256 * alpha);
      SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));

      // To draw the text, the layer is shifted to the right and down 1 Three pixels, representing the shadow effect 
      //DrawString  In the specified rectangle and with the specified  Brush  and  Font  Draws the specified text string. 
      grPhoto.DrawString(waterWords,                  //string of text
                    crFont,                     //font
                    semiTransBrush2,              //Brush
                    new PointF(xPosOfWm + 1, yPosOfWm + 1), //Position
                    StrFormat);

      // from 4 a  ARGB  Component ( alpha , red, green, and blue) values created  Color  Structure, and I'm going to set transparency to 153
      // This brush is a white brush depicting formal text 
      SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

      // The first 2 The second drawing of this graph is set at no 1 On the basis of the sub-depiction 
      grPhoto.DrawString(waterWords,         //string of text
                    crFont,                  //font
                    semiTransBrush,              //Brush
                    new PointF(xPosOfWm, yPosOfWm), //Position
                    StrFormat);

      //imgPhoto It's what we built to load the final shape Image object 
      //bmPhoto Is the container that we use to make graphics, for Bitmap object 
      imgPhoto = bmPhoto;
      // Release the resources that will be defined Graphics The instance grPhoto Release, grPhoto politics 
      grPhoto.Dispose();

      // will grPhoto save 
      imgPhoto.Save(targetImage, ImageFormat.Jpeg);
      imgPhoto.Dispose();

      return targetImage.Replace(PicturePath, "");
    }
  }

  /// <summary>
  ///  Load information about watermark images 
  /// </summary>
  public class WaterImage
  {
    public WaterImage()
    {

    }

    private string m_sourcePicture;
    /// <summary>
    ///  Source image address name ( With the suffix )

    /// </summary>
    public string SourcePicture
    {
      get { return m_sourcePicture; }
      set { m_sourcePicture = value; }
    }

    private string m_waterImager;
    /// <summary>
    ///  Name of watermark image ( With the suffix )
    /// </summary>
    public string WaterPicture
    {
      get { return m_waterImager; }
      set { m_waterImager = value; }
    }

    private float m_alpha;
    /// <summary>
    ///  Watermark image text transparency 
    /// </summary>
    public float Alpha
    {
      get { return m_alpha; }
      set { m_alpha = value; }
    }

    private ImagePosition m_postition;
    /// <summary>
    ///  The position of the watermark image or text in the image 
    /// </summary>
    public ImagePosition Position
    {
      get { return m_postition; }
      set { m_postition = value; }
    }

    private string m_words;
    /// <summary>
    ///  The contents of the watermark text 
    /// </summary>
    public string Words
    {
      get { return m_words; }
      set { m_words = value; }
    }

  }
}

I believe that this article has a definite reference for your C# programming.


Related articles: