Using ASP. NET implementation to add image watermark to pictures sample code

Source: Internet
Author: User
Watermark on the picture I believe every programmer will encounter this demand, the following article mainly introduces the ASP. NET implementation of the image to add a picture watermark method, the text gives a complete example code, I believe that we have a certain reference value, the need for friends below to see it together.

Objective

This article mainly introduces to you the ASP. NET implementation of the image to add image watermark method, attention is the picture watermark, the need for friends can refer to the study, the following words do not say to see more detailed introduction bar.

Methods are as follows

First, write a class that writes a watermark to the image, and first create a ImageWriter class library (which contains enumeration types and methods)

Using system;using system.collections.generic;using system.linq;using system.text;using System.IO;using System.collections;using system.drawing;using system.drawing.drawing2d;using System.drawing.imaging;namespace imagewriter{///<summary>///Image processing class///</summary> public class Imagemanager {#region variable declaration start///<summary  >///enum: Watermark location///</summary> public enum Watermarkposition {//<summary>//Left upper//</summary> Lefttop,///<summary>//Left middle///</summary> Ieft,///<summary>///</summary> Le Ftbottom,///<summary>///</summary> Top,///<summary>///</summary> Cen ter,///<summary>///</summary> Bottom,//<summary>//right up/  Top,///<summary>///Right///</summary> Rightcenter,//<summary>//Right//</summary> Rigthbottom} #endregion Variable declaration ends #region constructor Start///&LT;summary>///constructor: Default///</summary> public Imagemanager () {} #endregion constructor ends #region Private Function starts//<summary& Gt Get: Picture Go extension (contains full path and its file name) lowercase string///</summary>//<param name= "path" > Picture path (contains full path, file name and extension): string</ param>//<returns> back: Picture Go extension (contains full path and its file name) lowercase string: string</returns> private String GetFileName (string Path) {return path. Remove (path. LastIndexOf ('. ')). ToLower (); }///<summary>//get: Picture with '. ' lowercase string extension starting with//</summary>//<param name= "path" > Picture path (contains full path, file name and extension): string</param>///< returns> return: Picture with '. ' The lowercase string extension that begins with: String</returns> private string GetExtension (string path) {return path. Remove (0, path. LastIndexOf ('. ')). ToLower (); }///<summary>///Get: System.Drawing.Imaging.ImageFormat object with a lowercase string extension beginning with '. '////</summary>//&LT;PA Ram name= "format" > ". ' Start with a lowercase string extension: string</param>//<returns> return: Image The System.Drawing.Imaging.ImageFormat object that corresponds to the lowercase string extension beginning with '. ' : SystEm. drawing.imaging.imageformat</returns> Private ImageFormat Getimageformat (string format) {switch (format) {case  ". bmp": Return imageformat.bmp;  Case ". EMF": Return imageformat.emf;  Case ". Exif": Return imageformat.exif;  Case ". gif": return imageformat.gif;  Case ". ico": Return Imageformat.icon;  Case ". png": Return imageformat.png;  Case ". tif": Return Imageformat.tiff;  Case ". Tiff": Return Imageformat.tiff;  Case ". Wmf": Return imageformat.wmf;  Default:return Imageformat.jpeg; }}///<summary>//Get: Enumerate Uinatlex.ToolBox.ImageManager.WatermarkPosition corresponding System.Drawing.Rectangle object///&LT ;/summary>//<param name= "Positon" > Enumeration Uinatlex.ToolBox.ImageManager.WatermarkPosition: uinatlex.toolbox.imagemanager.watermarkposition</param>//<param name= "X" > Original width: int</param>// <param name= "y" > Original height: int</param>//<param name= "x" > Watermark Width: int</param>//<param name= "Y" & gt; Watermark Height: int</param>//<param name= "I" > Margins: int</param>//<returns> Return: Enumeration Uinatlex.ToolBox.ImageManager.WatermarkPosition corresponding System.Drawing.Rectangle object: system.drawing.rectangle</ returns> private Rectangle Getwatermarkrectangle (watermarkposition positon, int x, int y, int x, int y, int i) {SWITC  H (positon) {case WatermarkPosition.LeftTop:return new Rectangle (i, I, x, y);  Case WatermarkPosition.Left:return New Rectangle (i, (y-y)/2, X, Y);  Case WatermarkPosition.LeftBottom:return New Rectangle (i, Y-y-I, X, Y);  Case WatermarkPosition.Top:return New Rectangle ((x-x)/2, I, X, y);  Case WatermarkPosition.Center:return New Rectangle ((x-x)/2, (Y-Y)/2, X, Y);  Case WatermarkPosition.Bottom:return New Rectangle ((x-x)/2, y-y-I, X, Y);  Case WatermarkPosition.RightTop:return New Rectangle (X-x-I, I, X, y);  Case WatermarkPosition.RightCenter:return New Rectangle (X-x-I, (y-y)/2, X, Y); Default:return New RectanglE (X-x-I, y-y-I, X, Y); }} #endregion the end of the private function #region text generation begins #endregion text generation ends #region Set Transparency start//<summary>////settings: Picture System.Drawing.Bitma P Object Transparency///</summary>//<param name= "Sbitmap" > Picture System.Drawing.Bitmap object: system.drawing.bitmap</ param>//<param name= "transparence" > Watermark Transparency (higher values, less transparency, range between 0.0f~1.0f): float</param>//<returns > Pictures system.drawing.bitmap:system.drawing.bitmap</returns> public Bitmap settransparence (Bitmap BM, float  transparence) {if (transparence = = 0.0f | | transparence = = 1.0f) throw new ArgumentException ("Transparency value can only be between 0.0f~1.0f");   Float[][] Floatarray = {new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, New float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, transparence, 0.0f}, new float[] {0.0  F, 0.0f, 0.0f, 0.0f, 1.0f}};  ImageAttributes imageattributes = new ImageAttributes (); Imageattributes.setcolormatrix (New ColormatriX (Floatarray), Colormatrixflag.default, Coloradjusttype.bitmap); Bitmap Bitmap = new Bitmap (BM. Width, BM.  Height);  Graphics graphics = graphics.fromimage (bitmap); Graphics. DrawImage (BM, new Rectangle (0, 0, BM. Width, BM. Height), 0, 0, BM. Width, BM.  Height, GraphicsUnit.Pixel, ImageAttributes); Graphics.  Dispose ();  Imageattributes.dispose (); Bm.  Dispose (); return bitmap; }///<summary>///settings: Picture System.Drawing.Bitmap object Transparency///</summary>//<param name= "Readpath" > Picture path (contains Full path, file name and extension): string</param>//<param name= "transparence" > Watermark Transparency (the higher the value, the lower the opacity, the range between 0.0f~1.0f): float< /param>///<returns> picture system.drawing.bitmap:system.drawing.bitmap</returns> public Bitmap Settransparence (string readpath, float transparence) {return settransparence (new Bitmap (Readpath), transparence);} #en Dregion Set the transparency end #region Add a watermark start//<summary>///Generate: System.Drawing.Bitmap object of the original drawing watermark///</summary>//<p Aram Name= "Sbitmap" > Original System.drawIng. Bitmap object: system.drawing.bitmap</param>//<param name= "Wbitmap" > Watermark System.Drawing.Bitmap object: system.drawing.bitmap</param>//<param name= "position" > Enumeration Uinatlex.toolbox.imagemanager.watermarkposition:uinatlex.toolbox.imagemanager.watermarkposition</param>/ <param name= "margin" > Watermark margin: int</param>///<returns> return: System.Drawing.Bitmap object of the original drawing watermark System.drawing.bitmap</returns> public Bitmap Createwatermark (Bitmap sbitmap, Bitmap Wbitmap, watermarkposition  position, int margin) {Graphics graphics = Graphics.fromimage (SBITMAP); Graphics. DrawImage (Wbitmap, getwatermarkrectangle (position, Sbitmap.width, Sbitmap.height, Wbitmap.width, Wbitmap.height,  margin)); Graphics.  Dispose ();  Wbitmap.dispose (); return sbitmap;  #endregion Add a watermark to the end #region picture cutting begins #endregion The picture is cut to the end #region Picture zoom start #endregion picture Zoom end #region Save the picture to the beginning of the file #region Normal save start// <summary>//Save: System.Drawing.Bitmap object to picture File///</summary>//<paraM name= "Bitmap" >system.drawing.bitmap object: system.drawing.bitmap</param>//<param name= "Writepath" > Save path (contains full path, file name and extension): string</param> public void Save (Bitmap Bitmap, string writepath) {try {Bitmap.  Save (Writepath, Getimageformat (GetExtension (Writepath))); Bitmap.  Dispose ();  } catch {throw new ArgumentException ("Picture Save Error"); }}////<summary>//Save: Object to Picture File///</summary>//<param name= "Readpath" > Original path (contains full path, file name and extension): Strin g</param>//<param name= "Writepath" > Save path (contains full path, file name and extension): string</param> public void Save (string Readpath, String writepath) {if (string.  Compare (Readpath, writepath) = = 0) throw new ArgumentException ("Source picture and destination image address");  try {Save (new Bitmap (Readpath), Writepath);  } catch {throw new ArgumentException ("Picture read error");  }} #endregion save end of normal save #region start #endregion text drawing save end #region Transparency Adjustment Save start//<summary>//Save: Set Transparency object to picture file// </summary>//<param name= "Sbitmap" > Picture SyStem. Drawing.bitmap object: system.drawing.bitmap</param>//<param name= "transparence" > Watermark Transparency (the higher the value, the lower the transparency, the range in 0.0f~ 1.0f): float</param>//<param name= "Writepath" > Save path (contains full path, file name and extension): string</param> public void Savetransparence (Bitmap Bitmap, float transparence, string writepath) {Save (Settransparence (Bitmap, transparence) , Writepath); }///<summary>///Save: Set the image of the transparency to the picture file///</summary>//<param name= "Readpath" > Original path (contains full path, file name and extension): s tring</param>//<param name= "transparence" > Watermark Transparency (higher values, less transparency, range between 0.0f~1.0f): float</param>// <param name= "Writepath" > Save path (contains full path, file name and extension): string</param> public void Savetransparence (string  Readpath, float transparence, string writepath) {Save (Settransparence (Readpath, transparence), Writepath);} #endregion Transparency Adjustment Save End #region Watermark Picture Save start//<summary>///Save: Draw Watermark object to picture file///</summary>//<param name= "Sbitmap" > Original System.Drawing.Bitmap object: system.drawing.bitmap</param>//<param name= "Wbitmap" > Watermark System.Drawing.Bitmap object: system.drawing.bitmap</param> <param name= "Position" > Enumeration Uinatlex.ToolBox.ImageManager.WatermarkPosition: uinatlex.toolbox.imagemanager.watermarkposition</param>//<param name= "margin" > Watermark margin: Int</param >//<param name= "Writepath" > Save path (contains full path, file name and extension): string</param> public void Savewatermark (Bitmap Sbitmap, Bitmap Wbitmap, watermarkposition position, int margin, string writepath) {Save (Createwatermark, Sbitmap p, position, margin), Writepath); }///<summary>///Save: Draw Watermark object to picture file///</summary>//<param name= "Readpath" > Picture path (contains full path, file name and extension): s tring</param>//<param name= "Watermarkpath" > Watermark picture Path (contains full path, file name and extension): string</param>//< param name= "transparence" > Watermark Transparency (higher values, less transparency, range between 0.0f~1.0f): float</param>//<param name= "position" > Enumeration Uinatlex.ToolBox.ImageManager.WatermarkPosition:Uinatlex.Toolbox.imagemanager.watermarkposition</param>//<param name= "margin" > Watermark margin: int</param>//< param name= "Writepath" > Save path (contains full path, file name and extension): string</param> public void Savewatermark (string readpath, String Watermarkpath, float transparence, watermarkposition position, int margin, string writepath) {if (string.  Compare (Readpath, writepath) = = 0) throw new ArgumentException ("Source picture and destination image address");  if (transparence = = 0.0f) Save (Readpath, Writepath); else if (transparence = = 1.0f) Savewatermark (new Bitmap (Readpath), New Bitmap (Watermarkpath), position, margin, Writepath  ); else Savewatermark (new Bitmap (Readpath), Settransparence (Watermarkpath, transparence), position, margin, writepath); #endregion the watermark picture is saved to the end #region picture cut save start #endregion picture cut save end #region Picture Zoom save start #endregion picture Zoom save start #endregion Save picture to file end}}/* called Very simple IM.  Savewatermark (original address, watermark address, transparency, watermark location, margin, save location); Uinatlex.ToolBox.ImageManager im = new Uinatlex.ToolBox.ImageManager (); Im. Savewatermark (Server.mappaTh ("/artwork. jpg"), Server.MapPath ("/watermark. jpg"), 0.5f, Uinatlex.ToolBox.ImageManager.WatermarkPosition.RigthBottom, 10, Server.MapPath ("/original. jpg")); */

Call the above class in the client page

protected void Page_Load (object sender, EventArgs e) {string newfilename = Server.MapPath ("img/") + DateTime.Now.Millisec Ond + "+ DateTime.Now.Second +". jpg "; Imagemanager im = new Imagemanager (); called Very simple IM. Savewatermark (original address, watermark address, transparency, watermark location, margin, saved to the location);  Im. Savewatermark (Server.MapPath ("img/chrysanthemum.jpg"), Server.MapPath ("Img/woshi.jpg"), 0.9f, ImageManager.WatermarkPosition.RigthBottom, NewFileName); }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.