您现在的位置: 365建站网 > 365文章 > 为图片添加水印

为图片添加水印

文章来源:365jz.com     点击数:541    更新时间:2009-09-17 10:28   参与评论
/Files/chengyq/WebApplicationH.rar

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Text;


namespace WebApplicationH
{
    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 (!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 (File.Exists(ImageToBePainted))
                    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
    }
}




///TextWatermarkPainter类

public 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", 30, 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.DarkSeaGreen;
                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.Y = newImage.Height - Font.Height;
                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
    }


 

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 WebApplicationH;
using System.Web.Hosting;//在托管应用程序的应用程序域内向托管应用程序提供应用程序管理功能和应用程序服务。无法继承此类。


namespace WebApplicationH
{
    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}", FileUpload1.PostedFile.FileName));
                    ///保存文件
                    FileUpload1.SaveAs(filePath);
                    ///加水印
                    this.AddWatermark(filePath, this.watermarkTextBox.Text);
                    image.ImageUrl = string.Format("~/{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.DarkGreen;
                painter.PaintWaterMark();
            }

        }
    }
}

 

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplicationH._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 style="font-family: 宋体, Arial, Helvetica, sans-serif; font-size: small; font-weight: normal; font-style: normal; font-variant: inherit; text-transform: none; color: #3333FF">
        水印文字:&nbsp;&nbsp;&nbsp; <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" Height="21px" Width="148px" />
        <br />加了水印的图像如下:
        <asp:Image ID="image" runat="server" />
    </div>

    </form>
</body>
</html>



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

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (541人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号