C uses the overlap of original image and watermark image to realize watermarking

  • 2021-09-24 23:29:32
  • OfStack

This paper gives an example of C # using the overlapping of original image and watermark image to realize watermarking. Share it for your reference, as follows:

Picture operation class


/// <summary>
///  Get 1 The scaled-down size of the pictures. 
/// </summary>
/// <param name="maxWidth"> Width to be reduced </param>
/// <param name="maxHeight"> Height to be reduced </param>
/// <param name="imageOriginalWidth"> Original width of picture </param>
/// <param name="imageOriginalHeight"> Original height of picture </param>
/// <returns> Returns the actual size of the picture after being scaled down </returns>
public static Size GetNewSize(int maxWidth, int maxHeight, int imageOriginalWidth, int imageOriginalHeight)
{
  double w = 0.0;
  double h = 0.0;
  double sw = Convert.ToDouble(imageOriginalWidth);
  double sh = Convert.ToDouble(imageOriginalHeight);
  double mw = Convert.ToDouble(maxWidth);
  double mh = Convert.ToDouble(maxHeight);
  if (sw < mw && sh < mh)
  {
    w = sw;
    h = sh;
  }
  else if ((sw / sh) > (mw / mh))
  {
    w = maxWidth;
    h = (w * sh) / sw;
  }
  else
  {
    h = maxHeight;
    w = (h * sw) / sh;
  }
  return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
}
/// <summary>
///  For a given 1 Pictures ( Image Object) is generated 1 Thumbnails of the specified size. 
/// </summary>
/// <param name="originalImage"> Original picture </param>
/// <param name="thumMaxWidth"> Width of thumbnail </param>
/// <param name="thumMaxHeight"> Height of thumbnail </param>
/// <returns> Returns the of the thumbnail Image Object </returns>
public static System.Drawing.Image GetThumbNailImage(System.Drawing.Image originalImage, int thumMaxWidth, int thumMaxHeight)
{
  Size thumRealSize = Size.Empty;
  System.Drawing.Image newImage = originalImage;
  Graphics graphics = null;
  try
  {
    thumRealSize = GetNewSize(thumMaxWidth, thumMaxHeight, originalImage.Width, originalImage.Height);
    newImage = new Bitmap(thumRealSize.Width, thumRealSize.Height);
    graphics = Graphics.FromImage(newImage);
    graphics.CompositingQuality = CompositingQuality.HighQuality;
    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphics.SmoothingMode = SmoothingMode.HighQuality;
    graphics.Clear(Color.Transparent);
    graphics.DrawImage(originalImage, new Rectangle(0, 0, thumRealSize.Width, thumRealSize.Height), new Rectangle(0, 0, originalImage.Width, originalImage.Height), GraphicsUnit.Pixel);
  }
  catch { }
  finally
  {
    if (graphics != null)
    {
      graphics.Dispose();
      graphics = null;
    }
  }
  return newImage;
}
/// <summary>
///  For a given 1 Image file generation 1 Thumbnails of the specified size. 
/// </summary>
/// <param name="originalImage"> Physical file address of picture </param>
/// <param name="thumMaxWidth"> Width of thumbnail </param>
/// <param name="thumMaxHeight"> Height of thumbnail </param>
/// <returns> Returns the of the thumbnail Image Object </returns>
public static System.Drawing.Image GetThumbNailImage(string imageFile, int thumMaxWidth, int thumMaxHeight)
{
  System.Drawing.Image originalImage = null;
  System.Drawing.Image newImage = null;
  try
  {
    originalImage = System.Drawing.Image.FromFile(imageFile);
    newImage = GetThumbNailImage(originalImage, thumMaxWidth, thumMaxHeight);
  }
  catch { }
  finally
  {
    if (originalImage != null)
    {
      originalImage.Dispose();
      originalImage = null;
    }
  }
  return newImage;
}
/// <summary>
///  For a given 1 Image file generation 1 Thumbnails of the specified size and save the thumbnails to the specified location. 
/// </summary>
/// <param name="originalImageFile"> Physical file address of picture </param>
/// <param name="thumbNailImageFile"> Physical file address of thumbnail </param>
/// <param name="thumMaxWidth"> Width of thumbnail </param>
/// <param name="thumMaxHeight"> Height of thumbnail </param>
public static void MakeThumbNail(string originalImageFile, string thumbNailImageFile, int thumMaxWidth, int thumMaxHeight)
{
  System.Drawing.Image newImage = GetThumbNailImage(originalImageFile, thumMaxWidth, thumMaxHeight);
  try
  {
    newImage.Save(thumbNailImageFile, ImageFormat.Jpeg);
  }
  catch
  { }
  finally
  {
    newImage.Dispose();
    newImage = null;
  }
}
/// <summary>
///  Will 1 Adjust the memory stream of 10 pictures to the specified size, and return the adjusted memory stream. 
/// </summary>
/// <param name="originalImageStream"> Memory flow of original picture </param>
/// <param name="newWidth"> Width of new picture </param>
/// <param name="newHeight"> Height of new picture </param>
/// <returns> Returns the memory stream of the adjusted picture </returns>
public static MemoryStream ResizeImage(Stream originalImageStream, int newWidth, int newHeight)
{
  MemoryStream newImageStream = null;
  System.Drawing.Image newImage = Globals.GetThumbNailImage(System.Drawing.Image.FromStream(originalImageStream), newWidth, newHeight);
  if (newImage != null)
  {
    newImageStream = new MemoryStream();
    newImage.Save(newImageStream, ImageFormat.Jpeg);
  }
  return newImageStream;
}
/// <summary>
///  Will 1 Memory streams are saved as disk files. 
/// </summary>
/// <param name="stream"> Memory flow </param>
/// <param name="newFile"> Destination disk file address </param>
public static void SaveStreamToFile(Stream stream, string newFile)
{
  if (stream == null || stream.Length == 0 || string.IsNullOrEmpty(newFile))
  {
    return;
  }
  byte[] buffer = new byte[stream.Length];
  stream.Position = 0;
  stream.Read(buffer, 0, buffer.Length);
  FileStream fileStream = new FileStream(newFile, FileMode.OpenOrCreate, FileAccess.Write);
  fileStream.Write(buffer, 0, buffer.Length);
  fileStream.Flush();
  fileStream.Close();
  fileStream.Dispose();
}
/// <summary>
///  Right 1 Add a picture watermark effect to the specified pictures. 
/// </summary>
/// <param name="imageFile"> Picture file address </param>
/// <param name="waterImage"> Watermark image ( Image Object) </param>
public static void CreateImageWaterMark(string imageFile, System.Drawing.Image waterImage)
{
  if (string.IsNullOrEmpty(imageFile) || !File.Exists(imageFile) || waterImage == null)
  {
    return;
  }
  System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imageFile);
  if (originalImage.Width - 10 < waterImage.Width || originalImage.Height - 10 < waterImage.Height)
  {
    return;
  }
  Graphics graphics = Graphics.FromImage(originalImage);
  int x = originalImage.Width - waterImage.Width - 10;
  int y = originalImage.Height - waterImage.Height - 10;
  int width = waterImage.Width;
  int height = waterImage.Height;
  graphics.DrawImage(waterImage, new Rectangle(x, y, width, height), 0, 0, width, height, GraphicsUnit.Pixel);
  graphics.Dispose();
  MemoryStream stream = new MemoryStream();
  originalImage.Save(stream, ImageFormat.Jpeg);
  originalImage.Dispose();
  System.Drawing.Image imageWithWater = System.Drawing.Image.FromStream(stream);
  imageWithWater.Save(imageFile);
  imageWithWater.Dispose();
}
/// <summary>
///  Right 1 Add text watermarking effect to the specified pictures. 
/// </summary>
/// <param name="imageFile"> Picture file address </param>
/// <param name="waterText"> Watermark text content </param>
public static void CreateTextWaterMark(string imageFile, string waterText)
{
  if (string.IsNullOrEmpty(imageFile) || string.IsNullOrEmpty(waterText) || !File.Exists(imageFile))
  {
    return;
  }
  System.Drawing.Image originalImage = System.Drawing.Image.FromFile(imageFile);
  Graphics graphics = Graphics.FromImage(originalImage);
  graphics.SmoothingMode = SmoothingMode.HighQuality;
  graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
  graphics.CompositingQuality = CompositingQuality.HighQuality;
  graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
  SolidBrush brush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
  Font waterTextFont = new Font("Arial", 16, FontStyle.Regular);
  SizeF waterTextSize = graphics.MeasureString(waterText, waterTextFont);
  float x = (float)originalImage.Width - waterTextSize.Width - 10F;
  float y = (float)originalImage.Height - waterTextSize.Height - 10F;
  graphics.DrawString(waterText, waterTextFont, brush, x, y);
  graphics.Dispose();
  brush.Dispose();
  MemoryStream stream = new MemoryStream();
  originalImage.Save(stream, ImageFormat.Jpeg);
  originalImage.Dispose();
  System.Drawing.Image imageWithWater = System.Drawing.Image.FromStream(stream);
  imageWithWater.Save(imageFile);
  imageWithWater.Dispose();
}
/// <summary>
///  Determines whether the uploaded component contains content. 
/// </summary>
/// <param name="fileUpload">ASP.NET 2.0 Standard upload component </param>
/// <returns> Returns if the data is valid True Otherwise, return False</returns>
public static bool IsAttachmentValid(FileUpload fileUpload)
{
  if (fileUpload != null &&
    fileUpload.PostedFile != null &&
    !string.IsNullOrEmpty(fileUpload.PostedFile.FileName) &&
    fileUpload.PostedFile.ContentLength > 0)
  {
    return true;
  }
  return false;
}


public class ImageHelper
{
  #region "  Relative path of watermark storage  "
  public static string GetLogoPath()
  {
    return "/images/logo.png";  /// Watermark path 
  }
  #endregion
  #region "  Image watermarking  "
  // <summary>
  //  Generate a picture watermark on a picture , This method does not support Gif Picture of type 
  // </summary>
  // <param name="Path"> Original server picture path </param>
  // <param name="Path_syp"> Generated picture path with picture watermark </param>
  // <param name="Path_sypf"> Watermark picture path </param>
  public static void MarkImage(Stream InUploadImagePath, string inLogoImagePath, string InSavePath)
  {
    System.Drawing.Image Image = System.Drawing.Image.FromStream(InUploadImagePath);
    System.Drawing.Image newimage = Image.FromFile(Current.Server.MapPath(inLogoImagePath));
    Graphics g = Graphics.FromImage(Image);
    g.DrawImage(newimage, new Rectangle(Image.Width - newimage.Width, Image.Height - newimage.Height, newimage.Width, newimage.Height), 0, 0, newimage.Width, newimage.Height, GraphicsUnit.Pixel);
    try {
      Image.Save(Current.Server.MapPath(InSavePath));
    }
    catch (Exception ex) {
    }
    finally {
      g.Dispose();
      Image.Dispose();
      newimage.Dispose();
    }
  }
  #endregion
}

For more readers interested in C # related content, please check the topics on this site: "Summary of C # Picture Operation Skills", "Summary of WinForm Control Usage", "C # Data Structure and Algorithm Tutorial", "C # Common Control Usage Tutorial", "C # Object-Oriented Programming Introduction Tutorial" and "Summary of C # Programming Thread Usage Skills"

I hope this article is helpful to everyone's C # programming.


Related articles: