天天看點

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
    }
}           

繼續閱讀