access_time 13 years ago language中文
more_vert

[C#] Asp.net 上传图片添加半透明图片或者文字水印的方法(二)

visibility 711 comment 0

在上一篇文章中讲到了关于C#上传图片添加文字水印的方法,这个章节中则是添加半透明的图片水印的方法。请参:http://hi.baidu.com/1987raymond/blog/item/017a6a4ee9a8ca01b2de0543.html

下面是ImageWatermarkPainter类的实现:

/* ***********************************************
* Author:          1987raymond
* Team:            Juice Sharing
* Created Time:    2009-3-11 20:53:14
* CopyRight:       Juice Sharing 团队版权所有 保留一切权利
* NameSpace:       Juice.Common.Drawing
* Class/Interface: ImageWatermarkPainter
* ***********************************************/

using System;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

namespace Juice.Common.Drawing
{
    /// <summary>
    /// 图片水印绘制器
    /// </summary>
    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 (!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;
                ///开始绘制水印
                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();
        }
    }
}

下面查看使用的方法:

default.aspx的内容如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
    <form id="form1" runat="server">
    <div>
        水印文字:<asp:TextBox ID="watermarkTextBox" runat="server"></asp:TextBox><br />
        选择上传图片:<asp:FileUpload ID="FileUpload1" runat="server" Width="189px" />
        <br />
        <asp:Button ID="uploadFileBtn" runat="server" Text="上传图片并且加文字水印"
            onclick="uploadFileBtn_Click" />
        <asp:Button ID="uploadAndAddImageBtn" runat="server" Text="上传图片并且添加半透明的图片水印"
            onclick="uploadAndAddImageBtn_Click" />
        <br />加了水印的图像如下:
        <asp:Image ID="image" runat="server" />
    </div>
    </form>
</body>
</html>

default.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 _Default : 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("~/{0}", Server.HtmlEncode(FileUpload1.PostedFile.FileName)));
                ///保存文件
                FileUpload1.SaveAs(filePath);
                ///加水印
                this.AddWatermark(filePath, this.watermarkTextBox.Text);
                image.ImageUrl = string.Format("~/{0}", Server.HtmlEncode(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.DarkGreen;
            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("~/{0}", Server.HtmlEncode(FileUpload1.PostedFile.FileName)));
                ///保存文件
                FileUpload1.SaveAs(filePath);
                ///加水印
                this.AddImageWatermark(filePath);
                image.ImageUrl = string.Format("~/{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("~/watermark.gif")))
        {
            painter.PaintWaterMark();
        }
    }

}

其显示效果如下:

点击“上传图片并且添加半透明的图片水印”按钮后效果如下:

上图中右下角的绿色的标志则是水印,需要说明的是:

WatermarkPainter painter = new ImageWatermarkPainter(filePath, 180, Server.MapPath("~/watermark.gif"))) 这个地方就是创建水印绘制器的实例,且为图片水印绘制器,透明度为180(介于0-255之间),水印图片的地址是~/watermark.gif

好了关于上传图片添加水印的方法就这些了,大家可以修改使得类更加的灵活和完善,如果以上有错误也请大家指教

info Last modified by Raymond 13 years ago copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

Follow Kontext

Get our latest updates on LinkedIn.

Want to contribute on Kontext to help others?

Learn more

More from Kontext