图片上传基类(带缩略,水印等等)

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.IO;
using System.Web;
using System.Drawing;

namespace YXKJ.WEB
{
    /// <summary>
    /// 通用上传文件类
    /// 周建波 于2008-2-28日
    /// </summary>
    public class FileUpLoadCommon
    {
        #region 私有属性字段
        private string _path;                   // 上传文件的路径
        private string _fileName;               // 文件名称
        private string _newFileName = "";            // 新的文件名
        private string _fileName_s;             // 缩略图文件名称
        private string _fileName_sy;            // 水印图文件名称(文字)
        private string _fileName_syp;           // 水印图文件名称(图片)
        private string _webFilePath;            // 服务器端文件路径
        private string _webFilePath_s;        // 服务器端缩略图路径
        private string _webFilePath_sy;        // 服务器端带水印图路径(文字)
        private string _webFilePath_syp;       // 服务器端带水印图路径(图片)
        private string _webFilePath_sypf;      // 服务器端水印图路径(图片)

        private string _errorMsg;               // 错误信息
        private bool _isDate = true;            // 是否加上日期
        private bool _isThumbnail = true;       // 是否产生缩图
        private bool _isWatermarkT = false;      // 是否产生水印文字
        private bool _isWatermarkP = false;      // 是否产生水印叠加图片
        private bool _isOnly = true;            // 是否只产生一个文件,原始文件+加水印文字+加水印图片


        //private bool _isImage = true;           // 是否只充许图片

        private int _width=35 ;               // 缩图宽度
        private int _height=25 ;               // 缩图高度
        private string _mode = "Auto";        // 缩图模式 "HW"://指定高宽缩放(可能变形)  "W"//指定宽,高按比例 "H"//指定高,宽按比例  "Cut"://指定高宽裁减(不变形) Auto:自动
        private string _addText = "YXKJ";   // 水印文字
        private string _addPicture = "~/inc/syimg/sy.gif";   // 水印图片

        private int _fileSize = 0;          // 图片大小
        private int _fileWidth = 0;         // 图片宽度
        private int _fileHeight = 0;        // 图片高度
        private string _fileType;           // 文件类型
        #endregion

        #region 属性 -- 旧文件名[只读]
        /// <summary>
        /// 旧文件名[只读]
        /// </summary>
        public string fileName
        {
            get
            {
                return _fileName;
            }
        }
        #endregion


        #region 返回服务器端文件路径[只读]
        /// <summary>
        /// 返回文件路径[只读]
        /// </summary>
        public string webfilepath
        {
            get
            {
                return _webFilePath;
            }
        }
        #endregion


        #region 返回服务器端缩略图片路径[只读]
        /// <summary>
        /// 返回服务器端缩略图片路径[只读]
        /// </summary>
        public string webfilepaths
        { get
           {
            return _webFilePath_s;
           }
        }
        #endregion

        #region 返回服务器端水印图片路径(文字)[只读]
        /// <summary>
        /// 返回服务器端水印图片路径(文字)[只读]
        /// </summary>
        public string webfilepathsy
        { get
            {
            return _webFilePath_sy;
            }
        }
        #endregion


        #region 显示错误信息
        /// <summary>
        /// 显示错误信息[只读]
        /// </summary>
        public string ErroMessage
        {
            get { return _errorMsg; }

        }
        #endregion


        #region 返回服务器端水印图片路径(图片)
        /// <summary>
        /// 返回服务器端水印图片路径(图片)[只读]
        /// </summary>
        public string webfilepathsyp
        {
            get { return _webFilePath_syp; }

        }
        #endregion

        #region 属性 -- 上传后新文件名
        /// <summary>
        /// 上传后新文件名[只读]
        /// </summary>
        public string newFileName
        {
            get
            {
                return _newFileName;
            }
        }
        #endregion

        #region 属性 -- 缩图文件名
        /// <summary>
        /// 缩图文件名[只读]
        /// </summary>
        public string fileName_s
        {
            get
            {
                return _fileName_s;
            }
        }
        #endregion

        #region 属性 -- 加文字水印的图片
        /// <summary>
        /// 加文字水印的图片[只读]
        /// </summary>
        public string fileName_sy
        {
            get
            {
                return _fileName_sy;
            }
        }
        #endregion

        #region 属性 -- 加图片水印的图片
        /// <summary>
        /// 加图片水印的图片[只读]
        /// </summary>
        public string fileName_syp
        {
            get
            {
                return _fileName_syp;
            }
        }
        #endregion

        #region 属性 -- 上传的文件的路径
        /// <summary>
        /// 上传的文件的路径[只读]
        /// </summary>
        public string path
        {
            get
            {
                return _path;
            }
        }
        #endregion

        #region 属性 -- 文件大小
        /// <summary>
        /// 文件大小[只读]
        /// </summary>
        public int fileSize
        {
            get
            {
                return _fileSize;
            }
        }
        #endregion

        #region 属性 -- 图片原始的宽度
        /// <summary>
        /// 图片原始的宽度[只读]
        /// </summary>
        public int fileWidth
        {
            get
            {
                return _fileWidth;
            }
        }
        #endregion

        #region 属性 -- 图片原始的高度
        /// <summary>
        /// 图片原始的高度[只读]
        /// </summary>
        public int fileHeight
        {
            get { return _fileHeight; }
        }
        #endregion

        #region 属性 -- 文件的类型
        /// <summary>
        /// 文件的类型[只读]
        /// </summary>
        public string fileType
        {
            get { return _fileType; }
        }
        #endregion

        #region 属性 -- 设置水印文字
        /// <summary>
        /// 设置水印文字[只写]
        /// </summary>
        public string addText
        {
            set { _addText = value; }
        }
        #endregion

        #region 属性 -- 设置水印图片
        /// <summary>
        /// 设置水印图片[只写]
        /// </summary>
        public string addPicture
        {
            set { _addPicture = value; }
        }
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数(../file/)该路径可以根据实际使用更改,设置True为根据时间生成子文件夹
        /// </summary>
        public FileUpLoadCommon()
            : this("../File/", true)
        {

        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="isDate">是否按日期创建目录</param>
        public FileUpLoadCommon(string filePath, bool isDate)
        {
            _path = filePath;
            _isDate = isDate;
            if (_isDate)
                _path += DateTime.Now.ToString("yyyyMMdd") + "/";

            string p = HttpContext.Current.Server.MapPath(_path);
            //如果目录不存在,将创建目录
            if (!Directory.Exists(p))
                Directory.CreateDirectory(p);
        }
        #endregion

        #region 方法 -- 保存文件

        /// <summary>
        /// 指定缩图的宽高
        /// </summary>
        /// <param name="fu">文件类型</param>
        /// <param name="Width">宽</param>
        /// <param name="Height">高</param>
        /// <returns></returns>
        public bool SaveImage(FileUpload fu, int Width, int Height)
        {
            _width = Width;
            _height = Height;
            return SaveFile(fu, true);
        }

        /// <summary>
        /// 指定缩图的宽高
        /// </summary>
        /// <param name="fu">文件类型</param>
        /// <param name="Width">宽</param>
        /// <param name="Height">高</param>
        /// <param name="Mode">缩图模式 "HW"://指定高宽缩放(可能变形)  "W"//指定宽,高按比例 "H"//指定高,宽按比例  "Cut"://指定高宽裁减(不变形) </param>
        /// <returns></returns>
        public bool SaveImage(FileUpload fu, int Width, int Height, string Mode)
        {
            _width = Width;
            _height = Height;
            _mode = Mode;
            return SaveFile(fu, true);
        }
        #endregion


        #region "检测当前字符是否在以,号分开的字符串中(xx,sss,xaf,fdsf)"
        /// <summary>
        /// 检测当前字符是否在以,号分开的字符串中(xx,sss,xaf,fdsf)
        /// </summary>
        /// <param name="TempChar">需检测字符</param>
        /// <param name="TempStr">待检测字符串</param>
        /// <returns>存在true,不存在false</returns>
        public static bool Check_Char_Is(string TempChar, string TempStr)
        {
            bool rBool = false;
            if (TempChar != null && TempStr != null)
            {
                string[] TempStrArray = TempStr.Split(',');
                for (int i = 0; i < TempStrArray.Length; i++)
                {
                    if (TempChar == TempStrArray[i].Trim())
                    {
                        rBool = true;
                        break;
                    }
                }
            }
            return rBool;
        }
        #endregion


        #region 方法 -- 保存文件
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="fu">上传文件对象</param>
        /// <param name="IsImage">是否邮件</param>
        public bool SaveFile(FileUpload fu, bool IsImage)
        {
            if (fu.HasFile)
            {
                string fileContentType = fu.PostedFile.ContentType;

                string name = fu.PostedFile.FileName;                        // 客户端文件路径
                FileInfo file = new FileInfo(name);
                _fileType = fu.PostedFile.ContentType;
                _fileSize = fu.PostedFile.ContentLength;

                bool isfileTypeImages = false;
                if (fileContentType == "image/x-png" || fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
                {
                    isfileTypeImages = true;
                }

                if (IsImage == true && isfileTypeImages == false)
                {
                    _errorMsg = "文件类型不是图片!";
                    fu.Dispose();
                    return false;
                }

                //检测文件扩展名是否正确
                //"html,txt,doc,jpg"这些内容可以根据数据库,也可以根据webconfig.xml设置
                //文件允许大小[这里为(2000)即2M]也可以根据数据库或者 webconfig.xml设置
                if (!Check_Char_Is(file.Extension.Substring(1).ToLower(), "html,txt,doc,jpg"))
                {
                    _errorMsg = string.Format("文件扩展名不符合系统需求:{0}", "html,txt,doc,jpg");
                    fu.Dispose();
                    return false;
                }
                if (_fileSize / 1024 > 2000)
                {
                    _errorMsg = string.Format("上传文件超过系统允许大小:{0}K", 2000);
                    fu.Dispose();
                    return false;
                }


                _fileName = file.Name;                                // 文件名称
                _newFileName = CreateFileName() + file.Extension;
                _webFilePath = HttpContext.Current.Server.MapPath(_path + _newFileName);         // 服务器端文件路径

                if (isfileTypeImages)//如果是图片
                {
                    _fileName_s = "s_" + _newFileName;                      // 缩略图文件名称
                    if (_isOnly)
                    {
                        _fileName_sy = _newFileName;                     // 水印图文件名称(文字)
                        _fileName_syp = _newFileName;                    // 水印图文件名称(图片)
                    }
                    else
                    {
                        _fileName_sy = "sy_" + _newFileName;                     // 水印图文件名称(文字)
                        _fileName_syp = "syp_" + _newFileName;                    // 水印图文件名称(图片)
                    }


                    _webFilePath_s = HttpContext.Current.Server.MapPath(_path + _fileName_s);     // 服务器端缩略图路径
                    _webFilePath_sy = HttpContext.Current.Server.MapPath(_path + _fileName_sy);     // 服务器端带水印图路径(文字)
                    _webFilePath_syp = HttpContext.Current.Server.MapPath(_path + _fileName_syp);    // 服务器端带水印图路径(图片)
                    _webFilePath_sypf = HttpContext.Current.Server.MapPath(_addPicture);   // 服务器端水印图路径(图片)   

                    //检查文件是否存在
                    if (!File.Exists(_webFilePath))
                    {
                        try
                        {
                            fu.SaveAs(_webFilePath);                                 // 使用 SaveAs 方法保存文件    

                            if (_isWatermarkT)
                                AddShuiYinWord(_webFilePath, _webFilePath_sy);
                            if (_isWatermarkP)
                                AddShuiYinPic(_webFilePath, _webFilePath_syp, _webFilePath_sypf);
                            if (_isThumbnail)
                                MakeThumbnail(_webFilePath, _webFilePath_s, _width, _height, _mode);   // 生成缩略图方法

                            // 只有上传完了,才能获取图片大小
                            if (File.Exists(_webFilePath))
                            {
                                System.Drawing.Image originalImage = System.Drawing.Image.FromFile(_webFilePath);
                                try
                                {
                                    _fileHeight = originalImage.Height;
                                    _fileWidth = originalImage.Width;
                                }
                                finally
                                {
                                    originalImage.Dispose();
                                }
                            }

                            _errorMsg = string.Format("提示:文件“{0}”成功上传,并生成“{1}”缩略图,文件类型为:{2},文件大小为:{3}B", _newFileName, _fileName_s, fu.PostedFile.ContentType, fu.PostedFile.ContentLength);
                            fu.Dispose();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            _errorMsg = "提示:文件上传失败,失败原因:" + ex.Message;
                        }
                    }
                    else
                    {


                        _errorMsg = "提示:文件已经存在,请重命名后上传";
                    }
                }
                else
                {
                    //上传文件
                    //检查文件是否存在
                    if (!File.Exists(_webFilePath))
                    {
                        try
                        {
                            fu.SaveAs(_webFilePath);                                 // 使用 SaveAs 方法保存文件
                            _errorMsg = string.Format("提示:文件“{0}”成功上传,并生成“{1}”缩略图,文件类型为:{2},文件大小为:{3}B", _newFileName, _fileName_s, fu.PostedFile.ContentType, fu.PostedFile.ContentLength);
                            fu.Dispose();
                            return true;
                        }
                        catch (Exception ex)
                        {
                            _errorMsg = "提示:文件上传失败,失败原因:" + ex.Message;
                        }
                    }
                    else
                        _errorMsg = "提示:文件已经存在,请重命名后上传";

                }
            }
            fu.Dispose();
            return false;
        }
        #endregion

        #region 方法 -- 创建新的文件名
        /// <summary>
        /// 创建新的文件名
        /// </summary>
        /// <returns></returns>
        public string CreateFileName()
        {
            string guid = System.Guid.NewGuid().ToString().ToLower();
            guid = guid.Replace("-", "");

            return DateTime.Now.ToString("yyyyMMddhhmmss") + guid.Substring(0, 4);
        }
        #endregion

        #region 方法 -- 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename"></param>
        public static void DeleteFile(string filename)
        {
            string s = HttpContext.Current.Server.MapPath(filename);
            if (File.Exists(s))
            {
                try
                {
                    File.Delete(s);
                }
                catch
                { }
            }
        }
        #endregion

        #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 void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth = width;
            int toheight = height;

            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            if (ow < towidth && oh < toheight)
            {
                originalImage.Save(thumbnailPath);
            }
            else
            {

                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;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    case "AUTO": //自动适应高度
                        if (ow > oh)
                        {
                            //newwidth = 200;
                            toheight = (int)((double)oh / (double)ow * (double)towidth);
                        }
                        else
                        {
                            //newheight = 200;
                            towidth = (int)((double)ow / (double)oh * (double)toheight);
                        }
                        break;
                    default:
                        break;
                }

                //进行缩图
                Bitmap img = new Bitmap(towidth, toheight);
                img.SetResolution(72f, 72f);
                Graphics gdiobj = Graphics.FromImage(img);
                gdiobj.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                gdiobj.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                gdiobj.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                gdiobj.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0,
                                towidth, toheight);
                Rectangle destrect = new Rectangle(0, 0,
                                towidth, toheight);
                gdiobj.DrawImage(originalImage, destrect, 0, 0, ow,
                                oh, GraphicsUnit.Pixel);
                System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
                ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
                System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
                try
                {
                    if (ici != null)
                    {
                        img.Save(thumbnailPath, ici, ep);
                    }
                    else
                    {
                        img.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    gdiobj.Dispose();
                    img.Dispose();
                }
            }
            originalImage.Dispose();
        }


        private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            System.Drawing.Imaging.ImageCodecInfo[] encoders;
            encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

        #endregion

        #region 方法 -- 在图片上增加文字水印
        /**/
        /// <summary>
        /// 在图片上增加文字水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_sy">生成的带文字水印的图片路径</param>
        protected void AddShuiYinWord(string Path, string Path_sy)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(image, 0, 0, image.Width, image.Height);
            System.Drawing.Font f = new System.Drawing.Font("Verdana", 16);
            System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Blue);

            g.DrawString(_addText, f, b, 15, 15);
            g.Dispose();

            image.Save(Path_sy);
            image.Dispose();
        }
        #endregion

        #region 方法 -- 在图片上生成图片水印
        /**/
        /// <summary>
        /// 在图片上生成图片水印
        /// </summary>
        /// <param name="Path">原服务器图片路径</param>
        /// <param name="Path_syp">生成的带图片水印的图片路径</param>
        /// <param name="Path_sypf">水印图片路径</param>
        protected void AddShuiYinPic(string Path, string Path_syp, string Path_sypf)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
            System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_sypf);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            g.DrawImage(copyImage, new System.Drawing.Rectangle(image.Width - copyImage.Width, image.Height - copyImage.Height, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, System.Drawing.GraphicsUnit.Pixel);
            g.Dispose();

            image.Save(Path_syp);
            image.Dispose();
        }
        #endregion
    }
}



以下介绍如何使用

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MyOffice_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:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
    </form>
</body>
</html>


CS文件

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using YXKJ.WEB;//添加命名空间的引用

//周建波
//2008-2-28
public partial class MyOffice_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (this.FileUpload1.PostedFile.FileName != "")
        {
            FileUpLoadCommon up = new FileUpLoadCommon();

            up.CreateFileName();
            up.SaveFile(FileUpload1, false);
            this.Label1.Text= up.webfilepath;
  
       
        }

    }
}

原文地址:https://www.cnblogs.com/zjba2/p/1085094.html