前两天分别分享了ASP.NET上传文件和如何使用Photoshop制作半透明水印,今天把上传和添加水印结合起来,教大家ASP.NET上传图片并添加文字水印、图片水印的方法(含源代码)
添加文字水印
在水印文字的文本框内输入文字,上传图片,点击【上传图片并添加文字水印】按钮,即可在下方得到添加了文字水印后的图片
添加图片水印
事先准备水印图片watermark.png放在指定目录内,然后上传图片,点击【上传图片并添加半透明的图片水印】按钮,即可得到添加图片水印后的图片
源代码
该ASP.NET上传图片添加文字水印、图片水印的实例,包含三个主要文件:公共类文件 WatermarkPainter.cs、前台页面 watermark.aspx、后台C#代码 watermark.aspx.cs
公共类文件 WatermarkPainter.cs
using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; using System; namespace Juice.Common.Drawing { /// <summary> /// 图片水印绘制器 /// </summary> public abstract class WatermarkPainter : IDisposable { /// <summary> /// 构造函数 /// </summary> /// <param name="rawImagePath"></param> /// <param name="alpha"></param> /// <param name="replaceRawImage"></param> protected WatermarkPainter(string rawImagePath, int alpha, bool replaceRawImage) { ImageToBePainted = rawImagePath; WatermarkAlpha = alpha; ReplaceRawImage = replaceRawImage; } /// <summary> /// 构造函数 /// </summary> /// <param name="rawImagePath"></param> /// <param name="alpha"></param> protected WatermarkPainter(string rawImagePath, int alpha) : this(rawImagePath, alpha, true) { } /// <summary> /// 为临时存储文件添加的后缀 /// </summary> private string m_TempFileSuffix = ".juice.watermark.temp"; /// <summary> /// 水印的透明度 /// </summary> private int m_WatermarkAlpha; /// <summary> /// 水印透明度 /// </summary> public int WatermarkAlpha { get { if (m_WatermarkAlpha > 255) m_WatermarkAlpha = 255; else if (m_WatermarkAlpha < 0) m_WatermarkAlpha = 0; return m_WatermarkAlpha; } set { m_WatermarkAlpha = value; } } private string m_ImageToBePainted; /// <summary> /// 添加水印的图片的物理路径 /// </summary> public string ImageToBePainted { get { return m_ImageToBePainted; } set { m_ImageToBePainted = value; } } private bool m_ReplaceRawImage; /// <summary> /// 是否用加了水印的图片替换原有的图片 /// </summary> public bool ReplaceRawImage { get { return m_ReplaceRawImage; } set { m_ReplaceRawImage = value; } } private string m_TempImagePath; /// <summary> /// 加了水印后的临时储存名称 /// </summary> protected string TempImagePath { get { if (string.IsNullOrEmpty(this.m_TempImagePath)) { StringBuilder s = new StringBuilder(ImageToBePainted); s.Append(this.m_TempFileSuffix); this.m_TempImagePath = s.ToString(); } return m_TempImagePath; } set { m_TempImagePath = value; } } /// <summary> /// 原始图像 /// </summary> private Image m_RawImage; /// <summary> /// 为图片添加水印 /// </summary> public void PaintWaterMark() { if (string.IsNullOrEmpty(ImageToBePainted)) return; if (!System.IO.File.Exists(ImageToBePainted)) throw new FileNotFoundException(string.Format("file {0} not found.", ImageToBePainted)); bool succeed; if (m_RawImage == null) m_RawImage = Image.FromFile(ImageToBePainted); ///原始的图片 using (Bitmap newImage = new Bitmap(m_RawImage.Width, m_RawImage.Height)) { ///创建绘制图片的图面 using (Graphics g = Graphics.FromImage(newImage)) { g.DrawImage(m_RawImage, 0, 0, m_RawImage.Width, m_RawImage.Height); ///开始绘制水印 succeed = AddWatermark(g, newImage); } if (succeed) ///将图片保存到临时的文件 newImage.Save(TempImagePath); if (m_RawImage != null) m_RawImage.Dispose(); } if (succeed && ReplaceRawImage) { //删除原来的文件 if (System.IO.File.Exists(ImageToBePainted)) System.IO.File.Delete(ImageToBePainted); FileInfo info = new FileInfo(TempImagePath); if (info.Exists) { info.MoveTo(ImageToBePainted); } } } /// <summary> /// 添加水印,继承类可以用来添加自己的水印 /// </summary> /// <param name="graphics"></param> /// <param name="newImage"></param> /// <returns></returns> protected abstract bool AddWatermark(Graphics graphics, Bitmap newImage); #region IDisposable 成员 public virtual void Dispose() { } #endregion } public sealed class TextWatermarkPainter : WatermarkPainter { /// <summary> /// 构造函数 /// </summary> /// <param name="rawImagePath"></param> /// <param name="alpha"></param> /// <param name="text"></param> public TextWatermarkPainter(string rawImagePath, int alpha, string text) : base(rawImagePath, alpha) { WatermarkText = text; } private Font m_Font; /// <summary> /// 水印文字的字体 /// </summary> public Font Font { get { if (null == m_Font) m_Font = new Font("Arial Black", 28, FontStyle.Bold, GraphicsUnit.Pixel); return m_Font; } set { m_Font = value; } } private Color m_FontColor; /// <summary> /// 字体颜色 /// </summary> public Color FontColor { get { if (m_FontColor == null) m_FontColor = Color.DeepPink; return m_FontColor; } set { m_FontColor = value; } } private string m_WatermarkText; /// <summary> /// 水印的文字 /// </summary> public string WatermarkText { get { return m_WatermarkText; } set { m_WatermarkText = value; } } /// <summary> /// 实现添加水印的方法 /// </summary> /// <param name="graphics"></param> /// <param name="newImage"></param> /// <returns></returns> protected override bool AddWatermark(Graphics graphics, Bitmap newImage) { if (string.IsNullOrEmpty(WatermarkText)) return true; using (SolidBrush brush = new SolidBrush(Color.FromArgb(WatermarkAlpha, FontColor.R, FontColor.G, FontColor.B))) { Font font; ///添加文字位置 PointF f = new PointF(); float totalWidth = Font.Size * WatermarkText.Length; //f.X = newImage.Width - totalWidth - 100; f.X = (newImage.Width - totalWidth+100)/2; f.Y = (newImage.Height - Font.Height)/2; // f.Y = newImage.Height/2; if (f.X < 0) { ///自动调整字体的大小 float width = newImage.Width / WatermarkText.Length; font = new Font(Font.FontFamily, width, GraphicsUnit.Pixel); } else font = Font; graphics.DrawString(WatermarkText, font, brush, f); } return true; } #region IDisposable 成员 public override void Dispose() { Font.Dispose(); base.Dispose(); } #endregion } public sealed class ImageWatermarkPainter : WatermarkPainter { /// <summary> /// 构造函数 /// </summary> /// <param name="rawImagePath"></param> /// <param name="alpha"></param> /// <param name="watermarkImage"></param> public ImageWatermarkPainter(string rawImagePath, int alpha, string watermarkImage) : base(rawImagePath, alpha) { WatermarkImagePath = watermarkImage; } private string m_WatermarkImagePath; /// <summary> /// 水印图片路径 /// </summary> public string WatermarkImagePath { get { return m_WatermarkImagePath; } set { m_WatermarkImagePath = value; } } private Image m_WatermarkImage; /// <summary> /// 水印图片对象 /// </summary> public Image WatermarkImage { get { if (null == m_WatermarkImage) m_WatermarkImage = Image.FromFile(WatermarkImagePath); return m_WatermarkImage; } } /// <summary> /// 添加水印 /// </summary> /// <param name="graphics"></param> /// <param name="newImage"></param> /// <returns></returns> protected override bool AddWatermark(Graphics graphics, Bitmap newImage) { if (string.IsNullOrEmpty(WatermarkImagePath)) return false; if (!System.IO.File.Exists(WatermarkImagePath)) throw new FileNotFoundException(string.Format("file {0} not found.", WatermarkImagePath)); if ((WatermarkImage.Width + 10) > newImage.Width || (WatermarkImage.Height + 10) > newImage.Height) return false; using (ImageAttributes attributes = new ImageAttributes()) { float alpha = WatermarkAlpha / 255.0f; float[][] colorMatrixElements = { 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, alpha, 0.0f}, new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f} }; ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); ///设置颜色调整矩阵 attributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); ///水印图片的位置,默认为右下角 //int x = newImage.Width - WatermarkImage.Width - 10; //int y = newImage.Height - WatermarkImage.Height - 10; int x = (newImage.Width - WatermarkImage.Width - 10)/2; int y = (newImage.Height - WatermarkImage.Height)/2; ///开始绘制水印 graphics.DrawImage(WatermarkImage, new Rectangle(x, y, WatermarkImage.Width, WatermarkImage.Height), 0, 0, WatermarkImage.Width, WatermarkImage.Height, GraphicsUnit.Pixel, attributes); } return true; } public override void Dispose() { if (null != WatermarkImage) WatermarkImage.Dispose(); base.Dispose(); } } }
前台页面 watermark.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="watermark.aspx.cs" Inherits="demo_watermark" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>添加水印图片</title> </head> <body> <center> <form id="form1" runat="server"> <table width="550" style="text-align:left" > <tr style="text-align:left"> <td style="text-align:left" >水印文字:</td> <td colspan="3"><asp:TextBox ID="watermarkTextBox" runat="server" Width="220px"></asp:TextBox></td> </tr> <tr> <td>选择上传图片:</td> <td colspan="3"><asp:FileUpload ID="FileUpload1" runat="server" Width="300px" /></td> </tr> <tr> <td colspan="2"> <asp:Button ID="uploadFileBtn" runat="server" Text="上传图片并添加文字水印" onclick="uploadFileBtn_Click" /> </td> <td colspan="2"> <asp:Button ID="uploadAndAddImageBtn" runat="server" Text="上传图片并添加半透明的图片水印" onclick="uploadAndAddImageBtn_Click" /> </td> </tr> </table> <br />加了水印的图像如下: <hr/> <asp:Image ID="image" runat="server" /> </form> </center> </body> </html>
后台C#代码 watermark.aspx.cs
using System; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Juice.Common.Drawing; using System.Web.Hosting; public partial class demo_watermark : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void uploadFileBtn_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.watermarkTextBox.Text)) return; if (FileUpload1.HasFile) { string contentType = FileUpload1.PostedFile.ContentType; if (contentType.StartsWith("image/")) { string filePath = Server.MapPath(string.Format("~/upload/{0}", FileUpload1.PostedFile.FileName)); ///保存文件 FileUpload1.SaveAs(filePath); ///加水印 this.AddWatermark(filePath, this.watermarkTextBox.Text); image.ImageUrl = string.Format("~/upload/{0}", FileUpload1.PostedFile.FileName); } } } /// <summary> /// 添加水印 /// </summary> /// <param name="filePath"></param> /// <param name="watermaterText"></param> private void AddWatermark(string filePath, string watermaterText) { using (TextWatermarkPainter painter = new TextWatermarkPainter(filePath, 80, watermaterText)) { painter.FontColor = System.Drawing.Color.DeepPink; painter.PaintWaterMark(); } } protected void uploadAndAddImageBtn_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string contentType = FileUpload1.PostedFile.ContentType; if (contentType.StartsWith("image/")) { string filePath = Server.MapPath(string.Format("~/upload/{0}", Server.HtmlEncode(FileUpload1.PostedFile.FileName))); ///保存文件 FileUpload1.SaveAs(filePath); ///加水印 this.AddImageWatermark(filePath); image.ImageUrl = string.Format("~/upload/{0}", Server.HtmlEncode(FileUpload1.PostedFile.FileName)); } } } /// <summary> /// 添加图片水印 /// </summary> /// <param name="filePath"></param> private void AddImageWatermark(string filePath) { using (WatermarkPainter painter = new ImageWatermarkPainter(filePath, 180, Server.MapPath("~/demo/watermark.png"))) { painter.PaintWaterMark(); } } }
若在添加了文字水印后添加图片水印无变化,注意清理缓存。如有疑问,可致电postmaster@weisico.com学习交流