ASP.NET(C#)缩略图片,添加文字水印和图片水印

本小项目注释清楚,分别用的文件是Default.aspx、PFile.cs和Images(最终结果的文件)、Temporary(临时文件)、WtermarkPic(水印的附加)这3个文件夹;
如有发现有写得不好的地方,希望各位高手多多指教和包涵;

一:Defalut.aspx的文件内容:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UpLoadDemo._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="text-align: center">
        <div>
            水印文字:<asp:TextBox ID="txtText" runat="server"></asp:TextBox> 
            <asp:FileUpload ID="upLoad" runat="server" Width="250" Height="25" />   
            <asp:Button ID="btnUpLoad" runat="server" Text="上传" Width="50" OnClick="btnUpLoad_Click" /> H:<asp:TextBox
                ID="txtHeight" runat="server" Width="25" Text="100" MaxLength="4" /> W:<asp:TextBox
                    ID="txtWidth" runat="server" Text="100" Width="25" MaxLength="4" />
        </div>
        <div id="divMessage" runat="server" style="color: Red">
        </div>
        <div id="divSource" runat="server" visible="false">
            <asp:Label ID="lblSource" runat="server" Text="原图" /><br />
            <asp:Image ID="imgSource" runat="server" />
        </div>
        <div id="divThumbnail" runat="server" visible="false">
            <asp:Label ID="lblThumbnail" runat="server" Text="缩略图" /><br />
            <asp:Image ID="imgThumbnail" runat="server" />
        </div>
        <div id="divWatermark" runat="server" visible="false">
            <asp:Label ID="Label1" runat="server" Text="文字水印" /><br />
            <asp:Image ID="imgWatermark" runat="server" />
        </div>
        <div id="divWatermarkPic" runat="server" visible="false">
            <asp:Label ID="Label2" runat="server" Text="图片水印" /><br />
            <asp:Image ID="imgWatermarkPic" runat="server" />
        </div>
    </div>
    </form>
</body>
</html>



二:Defalut.aspx.cs的文件内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace UpLoadDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        /****
         * 功能点:
         * 根据用户所上传的图片进行缩略、添加文字水印和图片水印;
         * 
         * 实现方法:
         * 1:在客户端有TextBox的文本框,是需要进行水印处理的文字;
         * 2:FileUpload是用户需要选择的源文件;
         * 3:Button用于上传事件的处理;
         * 4:还有ID为txtHeight和txtWidth的文本框,用于设置需要缩略图片的宽度和高度;
         * 5:还有5个Image,用于显示图片处理的效果; 
         * 
         * */


        #region 点击上传的事件处理
        /// <summary>
        /// 点击上传的事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            string[] extensionArray = new string[] { ".BMP", ".GIF", ".JPG", ".JPEG", ".PNG", ".TIFF" };
            try
            {
                string message = string.Empty;
                //判断是否已经有上传的文件
                if (upLoad.HasFile)
                {
                    //获取上传的图片名称
                    string fileName = this.upLoad.FileName;
                    //把上传的图片保存到FileInfo的对象里面
                    FileInfo fi = new FileInfo(this.upLoad.FileName);
                    //获取上传的图片的扩展名
                    string FileExtension = fi.Extension.ToUpper();
                    //判断上传的图片是否符合图片的格式
                    if (!extensionArray.Contains(FileExtension))
                    {
                        this.divMessage.InnerText = "请上传.JPG、.PNG、GIF的图片文件..";
                        return;
                    }
                    //声明一个临时文件夹的变量
                    string folderPath = "~/Temporary/";
                    //声明存放最终处理好的文件夹变量
                    string newFolderPath = "~/Images/";
                    //获取当明的项目的路径加上文件名称
                    string sourcePath = Server.MapPath(folderPath) + fi.Name;
                    try
                    {
                        //把图片保存到临时的文件夹目录里面
                        this.upLoad.SaveAs(sourcePath);
                        this.divMessage.InnerText = "保存图片成功..";
                        this.divSource.Visible = true;
                        this.imgSource.Width = Unit.Pixel(450);
                        this.imgSource.ImageUrl = folderPath + fi.Name;
                    }
                    catch
                    {
                        this.divMessage.InnerText = "保存图片出现错误..";
                        return;
                    }
                    //获取从客户端转入的高度
                    int h = Convert.ToInt32(this.txtHeight.Text.Trim());
                    //获取从客户端转入的宽度
                    int w = Convert.ToInt32(this.txtWidth.Text.Trim());
                    //获取存放最终文件的物理路径
                    string newPath = Server.MapPath(newFolderPath);
                    /**
                     * 调用UPFileClass的MakeThumbnail()缩略的方法    
                     * 
                     * 第一个参数值为:源文件的物理路径
                     * 第二个参数值为:新的文件物理路径,中间加上"T_"是为了避免文件名冲突
                     * 第三个参数值为:需要缩略图片的高度
                     * 第四个参数值为:需要缩略图片的宽度
                     * 第五个参数值为:缩略图片的方式(HW:指定高宽缩放(会变形);W:指定宽,高按比例;H:指定高,指定高,宽按比例;CUT:指定高宽裁减(不变形)) 
                     * */
                    Dictionary<string, string> di = UPFileClass.MakeThumbnail(sourcePath, newPath + "T_" + fileName, h, w, "H");
                    if (di["Success"].ToUpper() == "TRUE")
                    {
                        this.divThumbnail.Visible = true;
                        this.imgThumbnail.Width = Unit.Pixel(450);
                        this.imgThumbnail.ImageUrl = newFolderPath + "T_" + fileName;
                    }
                    /**
                     * 
                     * 调用UPFileClass的AddFileWatermark()添加文字水印的方法    
                     * 
                     * 第一个参数值为:源文件的物理路径
                     * 第二个参数值为:新的文件物理路径,中间加上"W_"是为了避免文件名冲突
                     * 第三个参数值为:需要添加显示的水印文字,注:可以不需要,因为在被调用方法的时候,已经赋了默认的值                 
                     * */
                    di = UPFileClass.AddFileWatermark(sourcePath, newPath + "W_" + fileName, this.txtText.Text);
                    if (di["Success"].ToUpper() == "TRUE")
                    {
                        this.divWatermark.Visible = true;
                        this.imgWatermark.Width = Unit.Pixel(450);
                        this.imgWatermark.ImageUrl = newFolderPath + "W_" + fileName;
                    }
                    //声明需添加图片的水印的图片路径
                    string wtermarkPicPath = Server.MapPath("~/WtermarkPic/") + "0df3d7ca7bcb0.jpg";
                    /**
                    * 
                    * 调用UPFileClass的AddFileWatermarkPic()添加文字水印的方法    
                    * 
                    * 第一个参数值为:源文件的物理路径
                    * 第二个参数值为:新的文件物理路径,中间加上"WPic_"是为了避免文件名冲突
                    * 第三个参数值为:需要添加显示的水印的图片物理路径,注:可以不需要               
                    * */
                    di = UPFileClass.AddFileWatermarkPic(sourcePath, newPath + "WPic_" + fileName, wtermarkPicPath);
                    if (di["Success"].ToUpper() == "TRUE")
                    {
                        this.divWatermarkPic.Visible = true;
                        this.imgWatermarkPic.Width = Unit.Pixel(450);
                        this.imgWatermarkPic.ImageUrl = newFolderPath + "WPic_" + fileName;
                    }
                    this.divMessage.InnerText = di["Message"];
                    //最后,删除临时的文件
                    //fi = new FileInfo(sourcePath);
                    //if (fi != null)
                    //    if (fi.Exists)
                    //        fi.Delete();
                }
                else
                {
                    this.divMessage.InnerText = "请上传图片...";
                }
            }
            catch (Exception ex)
            {
                this.divMessage.InnerText = "操作出现异常,消息为:" + ex.Message;
            }
        }
        #endregion
    }
}

三:UPFileClass.cs的文件内容:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;

namespace UpLoadDemo
{
    /// <summary>
    /// UPFileClass的摘要说明
    /// </summary>
    public class UPFileClass
    {
        //初始化为null的Dictionary的对象
        private static Dictionary<string, string> di = null;
        //声明isSuccess的变量(用于接收执行的方法是否为True或Flase)
        private static bool isSuccess = true;//赋予默认值
        //声明message的变量(用于接收执行的方法返回的信息)
        private static string message = string.Empty;

        #region 生成缩略图片
        /// <summary>
        /// 生成缩略图片
        /// </summary>
        /// <param name="originalImagePath">源图片路径</param>
        /// <param name="thumbnailPath">缩略图片路径</param>
        /// <param name="width">缩略图片的宽度</param>
        /// <param name="height">缩略图片的高度</param>
        /// <param name="mode">缩略方式</param>
        public static Dictionary<string, string> MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            try
            {
                //使用FromFile()方法从指定文件创建Image,参加为物理的路径
                Image originalImage = Image.FromFile(originalImagePath);
                //这里声明指定的高和宽,默认为参数传输进来的
                int towidth = width, toheight = height;
                //声明默认的图片坐标,默认值为0,0
                int x = 0, y = 0;
                //保存源图片的宽度和高度,赋了默认的源图片的宽度和高度
                int ow = originalImage.Width, oh = originalImage.Height;
                switch (mode.ToUpper())
                {
                    case "HW": //指定高宽缩放(会变形)
                        break;
                    case "W": //指定宽,高按比例
                        //公式为(源文件的高度 乘以 需要缩略的宽度 除以 源文件的宽度)
                        toheight = originalImage.Height * width / originalImage.Width;
                        break;
                    case "H":  //指定高,宽按比例
                        //公式为(源文件的高度 乘以 需要缩略的高度 除以 源文件的高度)
                        towidth = originalImage.Width * height / originalImage.Height;
                        break;
                    case "CUT": //指定高宽裁减(不变形)
                        /**
                         * (如果源图片的宽度 除以 源图片的高度) 大于 (指定的宽度 除以 指定的高度)
                         * */
                        if (((double)originalImage.Width / (double)originalImage.Height) > ((double)towidth / (double)toheight))
                        {
                            //oh = originalImage.Height;
                            //保存图片的高度=(源图片的高度 * 指定的宽度 / 指定的高度
                            ow = originalImage.Height * towidth / toheight;
                            //Y坐标等于0
                            y = 0;
                            //X坐标=(源图片的宽度 - 需要保存图片的宽度) / 2倍
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            //ow = originalImage.Width;
                            //保存图片的宽度=(源图片的宽度 * 指定的高度 / 指定的宽度
                            oh = originalImage.Width * height / towidth;
                            //X坐标等于0
                            x = 0;
                            //Y坐标=(源图片的高度 - 需要保存图片的高度) / 2倍
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }
                //新建一个bmp图片
                Image bitmap = new Bitmap(towidth, toheight);
                //新建一个画板(图形),调用FromImage()的方法创建一个Grphics,参加为Image的对象
                Graphics g = Graphics.FromImage(bitmap);
                //设置高质量插值法(此属性获取或者设置与此Graphics关联的插补模式)
                //取值请参考:http://msdn.microsoft.com/zh-cn/library/system.drawing.drawing2d.interpolationmode(v=vs.100).aspx
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                //设置高质量,低速度呈现平滑程度(此属性获取此Graphics的呈现质量)
                //取值请参加:http://msdn.microsoft.com/zh-cn/library/z714w2y9(v=vs.100).aspx
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //清空画布并以透明背景色填充
                g.Clear(Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                //此方法在指定位置并且按指定大小绘制指定的Image的指定部分
                /**
                 * 1:要绘制的Image;
                 * 2:指定所绘制图像的位置和大小;
                 * 3:指定Image对象中要绘制的部分;
                 * 4:指定所用的度量单位 
                 * */
                g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
                try
                {
                    //根据路径获取到FileInfo的对象
                    FileInfo fi = new FileInfo(thumbnailPath);
                    if (fi != null)
                        if (fi.Exists)  //如果该图片的对象已经存在,就先删除,否则,会出现相对应的异常
                            fi.Delete();
                    //以JPG格式保存缩略图片
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //此处,分别释放资源
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }
                message = "生成缩略图片成功..";
            }
            catch (Exception)
            {
                isSuccess = false;
                message = "生成缩略图片失败..";
            }
            di = new Dictionary<string, string>();
            di.Add("Success", isSuccess.ToString());
            di.Add("Message", message);
            return di;
        }
        #endregion

        #region 在图片上增加文字水印
        /// <summary>
        /// 在图片上增加文字水印
        /// </summary>
        /// <param name="path">原服务器图片路径</param>
        /// <param name="path_sy">生成的带文字水印的图片路径</param>
        /// <param name="text">在图片上需要显示的文字</param>
        public static Dictionary<string, string> AddFileWatermark(string path, string path_sy, string text = "CHINA")
        {
            try
            {
                //使用FromFile()方法从指定文件创建Image,参加为物理的路径
                Image image = Image.FromFile(path);
                //新建一个画板(图形),调用FromImage()的方法创建一个Grphics,参加为Image的对象
                Graphics g = Graphics.FromImage(image);
                //此方法在指定位置并且按指定大小绘制指定的Image的指定部分
                /**
                 * 1:要绘制的Image;
                 * 2:左上角的X坐标;
                 * 3:左上角的Y坐标;
                 * 4:所绘制图片的宽度;
                 * 5:所绘制图像的高度
                 * */
                g.DrawImage(image, 0, 0, image.Width, image.Height);
                //实例化字体对象
                /**
                 * 1:字体的格式
                 * 2:字体的大小
                 * */
                Font f = new Font("Verdana", 16);
                //指定颜色的对象,返回是Brush的对象
                Brush b = new SolidBrush(Color.Blue);
                //在指定位置并且用指定的Brush和Font对象绘制指定的文本字符串
                /**
                 * 1:要绘制的字符串;
                 * 2:定义字符串的文本格式;
                 * 3:所绘制文本的左上角的X坐标
                 * 4:所以制文本的左上角的Y坐标
                 * */
                g.DrawString(text, f, b, 15, 15);
                //释放资源
                g.Dispose();
                //根据路径获取到FileInfo的对象
                FileInfo fi = new FileInfo(path_sy);
                if (fi != null)
                    if (fi.Exists) //如果该图片的对象已经存在,就先删除,否则,会出现相对应的异常
                        fi.Delete();
                image.Save(path_sy);
                //释放资源
                image.Dispose();
                message = "添加文字水印成功";
            }
            catch
            {
                isSuccess = false;
                message = "添加文字水印出现错误..";
            }
            di = new Dictionary<string, string>();
            di.Add("Success", isSuccess.ToString());
            di.Add("Message", message);
            return di;
        }
        #endregion

        #region 在图片上生成图片水印
        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="path">原服务器图片路径</param>
        /// <param name="path_syp">生成的带图片水印的图片路径</param>
        /// <param name="path_sypf">水印图片路径</param>
        public static Dictionary<string, string> AddFileWatermarkPic(string path, string path_syp, string path_sypf)
        {
            try
            {
                //使用FromFile()方法从指定文件创建Image,参加为物理的路径
                Image image = Image.FromFile(path);
                //使用FromFile()方法从指定文件创建Image,参加为物理的路径,加载需要水印图片
                Image copyImage = Image.FromFile(path_sypf);
                //新建一个画板(图形),调用FromImage()的方法创建一个Grphics,参加为Image的对象
                Graphics g = Graphics.FromImage(image);
                /**
                 * 此方法在指定位置并且按指定大小绘制指定的Image的指定部分
                 * 
                 * 1:要绘制的Image
                 * 2:指定所绘制图片的位置和大小
                 * 3:左上角的X坐标
                 * 4:左上角的Y坐标
                 * 5:绘制的源图片部分的宽度
                 * 6:绘制的源图片部分的高度
                 * 7:所要绘制的单位
                 * */
                g.DrawImage(copyImage, new Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel);
                //释放资源
                g.Dispose();
                //根据路径获取到FileInfo的对象
                FileInfo fi = new FileInfo(path_syp);
                if (fi != null)
                    if (fi.Exists)//如果该图片的对象已经存在,就先删除,否则,会出现相对应的异常
                        fi.Delete();
                image.Save(path_syp);
                //释放资源
                image.Dispose();
                message = "添加图片水印成功..";
            }
            catch (Exception)
            {
                isSuccess = false;
                message = "添加图片水印失败..";
            }
            di = new Dictionary<string, string>();
            di.Add("Success", isSuccess.ToString());
            di.Add("Message", message);
            return di;
        }
        #endregion
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值