23
2014
07

Asp.Net 对图片进行水印(水印logo或文字)

1、水印时,在图片右下角水印网站logo

PicMark wm = new PicMark();
wm.DrawedImagePath = HttpContext.Current.Server.MapPath("..\\Images\\") + "logo.jpg"; //需要水印添加的图片
wm.ModifyImagePath = newpath; //原始路径
wm.LucencyPercent = 20; //透明度 1-100之间
wm.OutPath = newpath; //输出路径
wm.DrawImage();  //对图片进行水印处理:添加到图片右下角

2、水印时,在图片右下角水印一段文字或网站网址

PicMark wm = new PicMark();
wm.DrawedWord = "郑德才"; //需要水印添加的文字
wm.ModifyImagePath = newpath; //原始路径
wm.LGray = 0.5; //灰度 0-1之间
wm.OutPath = newpath; //输出路径
wm.DrawWords();  //对水印文字处理:添加到图片右下角


PicMark实例类代码:

using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;

/// <summary>
///PicMark 的摘要说明、图片水印logo
/// </summary>
public class PicMark
{
    public PicMark()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    #region "member fields"
    private string modifyImagePath = null;
    private string drawedWord = null;
    private string drawedImagePath = null;
    private int rightSpace;
    private int bottoamSpace;
    private int lucencyPercent = 70;
    private double lGray = 0.5;
    private string outPath = null;
    #endregion

    #region "propertys"
    /// <summary>
    /// 获取或设置要修改的图像路径
    /// </summary>
    public string ModifyImagePath
    {
        get { return this.modifyImagePath; }
        set { this.modifyImagePath = value; }
    }
    /// <summary>
    /// 获取或设置在画的图片路径(水印图片)
    /// </summary>
    public string DrawedImagePath
    {
        get { return this.drawedImagePath; }
        set { this.drawedImagePath = value; }
    }
    /// <summary>
    /// 获取或设置在画的水印文字
    /// </summary>
    public string DrawedWord
    {
        get { return this.drawedWord; }
        set { this.drawedWord = value; }
    }
    /// <summary>
    /// 获取或设置水印在修改图片中的右边距
    /// </summary>
    public int RightSpace
    {
        get { return this.rightSpace; }
        set { this.rightSpace = value; }
    }
    //获取或设置水印在修改图片中距底部的高度
    public int BottoamSpace
    {
        get { return this.bottoamSpace; }
        set { this.bottoamSpace = value; }
    }
    /// <summary>
    /// 获取或设置要绘制水印的透明度,注意是原来图片透明度的百分比
    /// </summary>
    public double LGray
    {
        get { return this.lGray; }
        set {   this.lGray = value; }
    }
    /// <summary>
    /// 获取或设置要绘制水印的透明度,注意是原来图片透明度的百分比
    /// </summary>
    public int LucencyPercent
    {
        get { return this.lucencyPercent; }
        set
        {
            if (value >= 0 && value <= 100)
                this.lucencyPercent = value;
        }
    }
    /// <summary>
    /// 获取或设置要输出图像的路径
    /// </summary>
    public string OutPath
    {
        get { return this.outPath; }
        set { this.outPath = value; }
    }
    #endregion

    #region "methods"
    /// <summary>
    /// 开始绘制水印
    /// </summary>
    public void DrawImage()
    {
        Image modifyImage = null;
        Image drawedImage = null;
        Graphics g = null;
        try
        {
            //建立图形对象
            modifyImage = Image.FromFile(this.ModifyImagePath);
            drawedImage = Image.FromFile(this.DrawedImagePath);
            g = Graphics.FromImage(modifyImage);
            //获取要绘制图形坐标
            int x = modifyImage.Width - (drawedImage.Width + 5);
            int y = modifyImage.Height - (drawedImage.Height + 5);
            //设置颜色矩阵
            float[][] matrixItems ={
                new float[] {1, 0, 0, 0, 0},
                new float[] {0, 1, 0, 0, 0},
                new float[] {0, 0, 1, 0, 0},
                new float[] {0, 0, 0, (float)this.LucencyPercent/100f, 0},
                new float[] {0, 0, 0, 0, 1}};
            ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
            ImageAttributes imgAttr = new ImageAttributes();
            imgAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            //绘制阴影图像
            g.DrawImage(
            drawedImage,
            new Rectangle(x, y, drawedImage.Width, drawedImage.Height),
            0, 0, drawedImage.Width, drawedImage.Height,
            GraphicsUnit.Pixel, imgAttr);
            //保存文件
            string[] allowImageType = { ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
            FileInfo file = new FileInfo(this.ModifyImagePath);
            ImageFormat imageType = ImageFormat.Gif;
            switch (file.Extension.ToLower())
            {
                case ".jpg":
                    imageType = ImageFormat.Jpeg;
                    break;
                case ".gif":
                    imageType = ImageFormat.Gif;
                    break;
                case ".png":
                    imageType = ImageFormat.Png;
                    break;
                case ".bmp":
                    imageType = ImageFormat.Bmp;
                    break;
                case ".tif":
                    imageType = ImageFormat.Tiff;
                    break;
                case ".wmf":
                    imageType = ImageFormat.Wmf;
                    break;
                case ".ico":
                    imageType = ImageFormat.Icon;
                    break;
                default:
                    break;
            }
            MemoryStream ms = new MemoryStream();
            modifyImage.Save(ms, imageType);
            byte[] imgData = ms.ToArray();
            modifyImage.Dispose();
            drawedImage.Dispose();
            g.Dispose();
            FileStream fs = null;
            if (this.OutPath == null || this.OutPath == "")
            {
                File.Delete(this.ModifyImagePath);
                fs = new FileStream(this.ModifyImagePath, FileMode.Create, FileAccess.Write);
            }
            else
            {
                fs = new FileStream(this.OutPath, FileMode.Create, FileAccess.Write);
            }
            if (fs != null)
            {
                fs.Write(imgData, 0, imgData.Length);
                fs.Close();
            }
        }
        finally
        {
            try
            {
                drawedImage.Dispose();
                modifyImage.Dispose();
                g.Dispose();
            }
            catch { ;}
        }
    }
    /// <summary> 
    /// 在图片上添加水印文字 
    /// </summary> 
    /// <param name="sourcePicture">源图片文件</param> 
    /// <param name="waterWords">需要添加到图片上的文字</param> 
    /// <param name="alpha">透明度</param> 
    /// <param name="position">位置</param> 
    /// <param name="PicturePath">文件路径</param> 
    /// <returns></returns> 
    public void DrawWords()
    {
        Image modifyImage = null;
        Graphics grPhoto = null;
        try
        {
            //建立图形对象
            modifyImage = Image.FromFile(this.ModifyImagePath);
            grPhoto = Graphics.FromImage(modifyImage);

            //获取图片的宽和高 
            int phWidth = modifyImage.Width;
            int phHeight = modifyImage.Height;

            //设置图形的品质 
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //将我们要添加水印的图片按照原始大小描绘(复制)到图形中 
            grPhoto.DrawImage(
             modifyImage,                                           //   要添加水印的图片 
             new Rectangle(0, 0, phWidth, phHeight), //  根据要添加的水印图片的宽和高 
             0,                                                     //  X方向从0点开始描绘 
             0,                                                     // Y方向  
             phWidth,                                            //  X方向描绘长度 
             phHeight,                                           //  Y方向描绘长度 
             GraphicsUnit.Pixel);                              // 描绘的单位,这里用的是像素 

            //根据图片的大小我们来确定添加上去的文字的大小 
            //在这里我们定义一个数组来确定
            int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

            //字体 
            Font crFont = null;
            //矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空 
            SizeF crSize = new SizeF();

            //利用一个循环语句来选择我们要添加文字的型号 
            //直到它的长度比图片的宽度小 
            for (int i = 0; i < 7; i++)
            {
                crFont = new Font("arial", sizes[i], FontStyle.Bold);

                //测量用指定的 Font 对象绘制并用指定的 StringFormat 对象格式化的指定字符串。 
                crSize = grPhoto.MeasureString(this.DrawedWord.Trim(), crFont);

                // ushort 关键字表示一种整数数据类型 
                if ((ushort)crSize.Width < (ushort)phWidth)
                    break;
            }

            int x = phWidth - (Convert.ToInt32(crSize.Width) - Convert.ToInt32(crSize.Width) / 2 + 5); //文字长度的中间位置
            int y = phHeight - (Convert.ToInt32(crSize.Height) + 5);

            //封装文本布局信息(如对齐、文字方向和 Tab 停靠位),显示操作(如省略号插入和国家标准 (National) 数字替换)和 OpenType 功能。 
            StringFormat StrFormat = new StringFormat();

            //定义需要印的文字居中对齐 
            StrFormat.Alignment = StringAlignment.Center;

            //SolidBrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。 
            //这个画笔为描绘阴影的画笔,呈灰色 
            int m_alpha = Convert.ToInt32(256 * this.LGray);
            SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));

            //描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果 
            //DrawString 在指定矩形并且用指定的 Brush 和 Font 对象绘制指定的文本字符串。 
            grPhoto.DrawString(this.DrawedWord.Trim(),                                    //string of text 
                                       crFont,                                         //font 
                                       semiTransBrush2,                            //Brush 
                                       new Point(x, y),  //Position 
                                       StrFormat);

            //保存文件
            string[] allowImageType = { ".jpg", ".gif", ".png", ".bmp", ".tiff", ".wmf", ".ico" };
            FileInfo file = new FileInfo(this.ModifyImagePath);
            ImageFormat imageType = ImageFormat.Gif;
            switch (file.Extension.ToLower())
            {
                case ".jpg":
                    imageType = ImageFormat.Jpeg;
                    break;
                case ".gif":
                    imageType = ImageFormat.Gif;
                    break;
                case ".png":
                    imageType = ImageFormat.Png;
                    break;
                case ".bmp":
                    imageType = ImageFormat.Bmp;
                    break;
                case ".tif":
                    imageType = ImageFormat.Tiff;
                    break;
                case ".wmf":
                    imageType = ImageFormat.Wmf;
                    break;
                case ".ico":
                    imageType = ImageFormat.Icon;
                    break;
                default:
                    break;
            }
            MemoryStream ms = new MemoryStream();
            modifyImage.Save(ms, imageType);
            byte[] imgData = ms.ToArray();
            modifyImage.Dispose();
            grPhoto.Dispose();
            FileStream fs = null;
            if (this.OutPath == null || this.OutPath == "")
            {
                File.Delete(this.ModifyImagePath);
                fs = new FileStream(this.ModifyImagePath, FileMode.Create, FileAccess.Write);
            }
            else
            {
                fs = new FileStream(this.OutPath, FileMode.Create, FileAccess.Write);
            }
            if (fs != null)
            {
                fs.Write(imgData, 0, imgData.Length);
                fs.Close();
            }
        }
        finally
        {
            try
            {
                modifyImage.Dispose();
                grPhoto.Dispose();
            }
            catch { ;}
        }
    }
    #endregion
}

效果图片:

« 上一篇下一篇 »

评论列表:

1.快乐易文  2014/7/26 17:10:06 回复该留言
谢谢你的分享
2.快乐易文  2014/8/2 13:37:05 回复该留言
好 感谢你的分享

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。