图片通用上传文件类(处理水印,缩略图)

/************************************************************************************
* Copyright (C) 2007 supesoft.com,All Rights Reserved *
* File: *
* FileUpLoadCommon.cs *
* Description: *
* 通用上传文件类 *
* Author: *
* Lzppcc *
* Lzppcc@hotmail.com *
* http://www.supesoft.com *
* Finish DateTime: *
* 2007年8月6日 *
* History: *
***********************************************************************************/
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Web.UI.WebControls;
  5. using System.IO;
  6. using System.Web;
  7. using System.Drawing;
  8. namespace FrameWork
  9. {
  10.     /// &ltsummary>
  11.     /// 通用上传文件类
  12.     /// </summary>
  13.     public class FileUpLoadCommon
  14.     {
  15.         #region "Private Variables"
  16.         private string _path;                   // 上传文件的路径
  17.         private string _fileName;               // 文件名称
  18.         private string _newFileName  ="";            // 新的文件名
  19.         private string _fileName_s;             // 缩略图文件名称
  20.         private string _fileName_sy;            // 水印图文件名称(文字)
  21.         private string _fileName_syp;           // 水印图文件名称(图片)
  22.         private string _webFilePath;            // 服务器端文件路径
  23.         private string _webFilePath_s;        // 服务器端缩略图路径
  24.         private string _webFilePath_sy;        // 服务器端带水印图路径(文字)
  25.         private string _webFilePath_syp;       // 服务器端带水印图路径(图片)
  26.         private string _webFilePath_sypf;      // 服务器端水印图路径(图片)
  27.         private string _errorMsg;               // 错误信息
  28.         private bool _isDate = true;            // 是否加上日期
  29.         private bool _isThumbnail = true;       // 是否产生缩图
  30.         private bool _isWatermarkT = false;      // 是否产生水印文字
  31.         private bool _isWatermarkP = false;      // 是否产生水印叠加图片
  32.         private bool _isOnly = true;            // 是否只产生一个文件,原始文件+加水印文字+加水印图片
  33.         //private bool _isImage = true;           // 是否只充许图片
  34.         private int _width = Common.UpImgWidth;               // 缩图宽度
  35.         private int _height = Common.UpImgHeight;               // 缩图高度
  36.         private string _mode = "Auto";        // 缩图模式 "HW"://指定高宽缩放(可能变形)  "W"//指定宽,高按比例 "H"//指定高,宽按比例  "Cut"://指定高宽裁减(不变形) Auto:自动 
  37.         private string _addText = "Moliyo.com";   // 水印文字
  38.         private string _addPicture = Common.UpLoadDir+"shuiyin.jpg";   // 水印文字
  39.         private int _fileSize = 0;          // 图片大小
  40.         private int _fileWidth = 0;         // 图片宽度
  41.         private int _fileHeight = 0;        // 图片高度
  42.         private string _fileType;           // 文件类型
  43.         #endregion
  44.         #region 属性 -- 旧文件名
  45.         /// &ltsummary>
  46.         /// 旧文件名
  47.         /// </summary>
  48.         public string fileName
  49.         {
  50.             get
  51.             {
  52.                 return _fileName;
  53.             }
  54.         }
  55.         #endregion
  56.         #region 属性 -- 上传后新文件名
  57.         /// &ltsummary>
  58.         /// 上传后新文件名
  59.         /// </summary>
  60.         public string newFileName
  61.         {
  62.             get
  63.             {
  64.                 return _newFileName;
  65.             }
  66.         }
  67.         #endregion
  68.         #region 属性 -- 缩图文件名
  69.         /// &ltsummary>
  70.         /// 缩图文件名
  71.         /// </summary>
  72.         public string fileName_s
  73.         {
  74.             get
  75.             {
  76.                 return _fileName_s;
  77.             }
  78.         }
  79.         #endregion
  80.         #region 属性 -- 加文字水印的图片
  81.         /// &ltsummary>
  82.         /// 加文字水印的图片
  83.         /// </summary>
  84.         public string fileName_sy
  85.         {
  86.             get
  87.             {
  88.                 return _fileName_sy;
  89.             }
  90.         }
  91.         #endregion
  92.         #region 属性 -- 加图片水印的图片
  93.         /// &ltsummary>
  94.         /// 加图片水印的图片
  95.         /// </summary>
  96.         public string fileName_syp
  97.         {
  98.             get
  99.             {
  100.                 return _fileName_syp;
  101.             }
  102.         }
  103.         #endregion
  104.         #region 属性 -- 上传的文件的路径
  105.         /// &ltsummary>
  106.         /// 上传的文件的路径
  107.         /// </summary>
  108.         public string path
  109.         {
  110.             get
  111.             {
  112.                 return _path;
  113.             }
  114.         }
  115.         #endregion
  116.         #region 属性 -- 文件大小
  117.         /// &ltsummary>
  118.         /// 文件大小
  119.         /// </summary>
  120.         public int fileSize
  121.         {
  122.             get
  123.             {
  124.                 return _fileSize;
  125.             }
  126.         }
  127.         #endregion
  128.         #region 属性 -- 图片原始的宽度
  129.         /// &ltsummary>
  130.         /// 图片原始的宽度
  131.         /// </summary>
  132.         public int fileWidth
  133.         {
  134.             get
  135.             {
  136.                 return _fileWidth;
  137.             }
  138.         }
  139.         #endregion
  140.         #region 属性 -- 图片原始的高度
  141.         /// &ltsummary>
  142.         /// 图片原始的高度
  143.         /// </summary>
  144.         public int fileHeight
  145.         {
  146.             get { return _fileHeight; }
  147.         }
  148.         #endregion
  149.         #region 属性 -- 文件的类型
  150.         /// &ltsummary>
  151.         /// 文件的类型
  152.         /// </summary>
  153.         public string fileType
  154.         {
  155.             get { return _fileType; }
  156.         }
  157.         #endregion
  158.         #region 属性 -- 设置水印文字
  159.         /// &ltsummary>
  160.         /// 设置水印文字
  161.         /// </summary>
  162.         public string addText
  163.         {
  164.             set { _addText = value; }
  165.         }
  166.         #endregion
  167.         #region 属性 -- 设置水印图片
  168.         /// &ltsummary>
  169.         /// 设置水印图片
  170.         /// </summary>
  171.         public string addPicture
  172.         {
  173.             set { _addPicture = value; }
  174.         }
  175.         #endregion
  176.         
  177.         #region 构造函数
  178.         /// &ltsummary>
  179.         /// 构造函数
  180.         /// </summary>
  181.         public FileUpLoadCommon()
  182.             : this("/public/"true)
  183.         {
  184.         }
  185.         /// &ltsummary>
  186.         /// 构造函数
  187.         /// </summary>
  188.         /// &ltparam name="filePath">文件路径</param>
  189.         /// &ltparam name="isDate">是否按日期创建目录</param>
  190.         public FileUpLoadCommon(string filePath, bool isDate)
  191.         {
  192.             _path = filePath;
  193.             _isDate = isDate;
  194.             if (_isDate)
  195.                 _path += DateTime.Now.ToString("yyyyMMdd") + "/";
  196.             string p = HttpContext.Current.Server.MapPath(_path);
  197.             //如果目录不存在,将创建目录
  198.             if (!Directory.Exists(p))
  199.                 Directory.CreateDirectory(p);
  200.         }
  201.         #endregion
  202.         #region 方法 -- 保存文件
  203.         /// &ltsummary>
  204.         /// 指定缩图的宽高
  205.         /// </summary>
  206.         /// &ltparam name="fu">文件类型</param>
  207.         /// &ltparam name="Width">宽</param>
  208.         /// &ltparam name="Height">高</param>
  209.         /// &ltreturns></returns>
  210.         public bool SaveImage(FileUpload fu, int Width, int Height)
  211.         {
  212.             _width = Width;
  213.             _height = Height;
  214.             return SaveFile(fu,true);
  215.         }
  216.         /// &ltsummary>
  217.         /// 指定缩图的宽高
  218.         /// </summary>
  219.         /// &ltparam name="fu">文件类型</param>
  220.         /// &ltparam name="Width">宽</param>
  221.         /// &ltparam name="Height">高</param>
  222.         /// &ltparam name="Mode">缩图模式 "HW"://指定高宽缩放(可能变形)  "W"//指定宽,高按比例 "H"//指定高,宽按比例  "Cut"://指定高宽裁减(不变形) </param>
  223.         /// &ltreturns></returns>
  224.         public bool SaveImage(FileUpload fu, int Width, int Height, string Mode)
  225.         {
  226.             _width = Width;
  227.             _height = Height;
  228.             _mode = Mode;
  229.             return SaveFile(fu,true);
  230.         }
  231.         #endregion
  232.         #region 方法 -- 保存文件
  233.         /// &ltsummary>
  234.         /// 保存文件
  235.         /// </summary>
  236.         /// &ltparam name="fu">上传文件对象</param>
  237.         /// &ltparam name="IsImage">是否邮件</param>
  238.         public bool SaveFile(FileUpload fu,bool IsImage)
  239.         {
  240.             if (fu.HasFile)
  241.             {
  242.                 string fileContentType = fu.PostedFile.ContentType;
  243.                 string name = fu.PostedFile.FileName;                        // 客户端文件路径
  244.                 FileInfo file = new FileInfo(name);
  245.                 _fileType = fu.PostedFile.ContentType;
  246.                 _fileSize = fu.PostedFile.ContentLength;
  247.                 bool isfileTypeImages = false;
  248.                 if (fileContentType == "image/x-png" || fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/pjpeg")
  249.                 {
  250.                     isfileTypeImages = true;
  251.                 }
  252.                 if (IsImage == true && isfileTypeImages == false)
  253.                 {
  254.                     _errorMsg = "文件类型不是图片!";
  255.                     fu.Dispose();
  256.                     return false;
  257.                 }
  258.                 
  259.                 //检测文件扩展名是否正确
  260.                 if (!Common.Check_Char_Is(file.Extension.Substring(1).ToLower(), FrameSystemInfo.GetSystemInfoTable.S_SystemConfigData.C_UploadFileExt.ToLower()))
  261.                 {
  262.                     _errorMsg = string.Format("文件扩展名不符合系统需求:{0}", FrameSystemInfo.GetSystemInfoTable.S_SystemConfigData.C_UploadFileExt);
  263.                     fu.Dispose();
  264.                     return false;
  265.                 }
  266.                 if (_fileSize / 1024 > FrameSystemInfo.GetSystemInfoTable.S_SystemConfigData.C_UploadSizeKb)
  267.                 {
  268.                     _errorMsg = string.Format("上传文件超过系统允许大小:{0}K", FrameSystemInfo.GetSystemInfoTable.S_SystemConfigData.C_UploadSizeKb);
  269.                     fu.Dispose();
  270.                     return false;  
  271.                 }
  272.                 _fileName = file.Name;                                // 文件名称
  273.                 _newFileName = CreateFileName() + file.Extension;
  274.                 _webFilePath = HttpContext.Current.Server.MapPath(_path + _newFileName);         // 服务器端文件路径
  275.                 if (isfileTypeImages)
  276.                 {
  277.                     _fileName_s = "s_" + _newFileName;                      // 缩略图文件名称
  278.                     if (_isOnly)
  279.                     {
  280.                         _fileName_sy = _newFileName;                     // 水印图文件名称(文字)
  281.                         _fileName_syp = _newFileName;                    // 水印图文件名称(图片)
  282.                     }
  283.                     else
  284.                     {
  285.                         _fileName_sy = "sy_" + _newFileName;                     // 水印图文件名称(文字)
  286.                         _fileName_syp = "syp_" + _newFileName;                    // 水印图文件名称(图片)
  287.                     }
  288.                     _webFilePath_s = HttpContext.Current.Server.MapPath(_path + _fileName_s);     // 服务器端缩略图路径
  289.                     _webFilePath_sy = HttpContext.Current.Server.MapPath(_path + _fileName_sy);     // 服务器端带水印图路径(文字)
  290.                     _webFilePath_syp = HttpContext.Current.Server.MapPath(_path + _fileName_syp);    // 服务器端带水印图路径(图片)
  291.                     _webFilePath_sypf = HttpContext.Current.Server.MapPath(_addPicture);   // 服务器端水印图路径(图片)    
  292.                     //检查文件是否存在
  293.                     if (!File.Exists(_webFilePath))
  294.                     {
  295.                         try
  296.                         {
  297.                             fu.SaveAs(_webFilePath);                                 // 使用 SaveAs 方法保存文件     
  298.                             if (_isWatermarkT)
  299.                                 AddShuiYinWord(_webFilePath, _webFilePath_sy);
  300.                             if (_isWatermarkP)
  301.                                 AddShuiYinPic(_webFilePath, _webFilePath_syp, _webFilePath_sypf);
  302.                             if (_isThumbnail)
  303.                                 MakeThumbnail(_webFilePath, _webFilePath_s, _width, _height, _mode);   // 生成缩略图方法
  304.                             // 只有上传完了,才能获取图片大小
  305.                             if (File.Exists(_webFilePath))
  306.                             {
  307.                                 System.Drawing.Image originalImage = System.Drawing.Image.FromFile(_webFilePath);
  308.                                 try
  309.                                 {
  310.                                     _fileHeight = originalImage.Height;
  311.                                     _fileWidth = originalImage.Width;
  312.                                 }
  313.                                 finally
  314.                                 {
  315.                                     originalImage.Dispose();
  316.                                 }
  317.                             }
  318.                             _errorMsg = string.Format("提示:文件“{0}”成功上传,并生成“{1}”缩略图,文件类型为:{2},文件大小为:{3}B", _newFileName, _fileName_s, fu.PostedFile.ContentType, fu.PostedFile.ContentLength);
  319.                             fu.Dispose();
  320.                             return true;
  321.                         }
  322.                         catch (Exception ex)
  323.                         {
  324.                             _errorMsg = "提示:文件上传失败,失败原因:" + ex.Message;
  325.                         }
  326.                     }
  327.                     else
  328.                     {
  329.                         _errorMsg = "提示:文件已经存在,请重命名后上传";
  330.                     }
  331.                 }
  332.                 else
  333.                 {
  334.                     //上传文件
  335.                     //检查文件是否存在
  336.                     if (!File.Exists(_webFilePath))
  337.                     {
  338.                         try
  339.                         {
  340.                             fu.SaveAs(_webFilePath);                                 // 使用 SaveAs 方法保存文件
  341.                             _errorMsg = string.Format("提示:文件“{0}”成功上传,并生成“{1}”缩略图,文件类型为:{2},文件大小为:{3}B", _newFileName, _fileName_s, fu.PostedFile.ContentType, fu.PostedFile.ContentLength);
  342.                             fu.Dispose();
  343.                             return true;
  344.                         }
  345.                         catch (Exception ex)
  346.                         {
  347.                             _errorMsg = "提示:文件上传失败,失败原因:" + ex.Message;
  348.                         }
  349.                     }
  350.                     else
  351.                         _errorMsg = "提示:文件已经存在,请重命名后上传";
  352.                 }
  353.             }
  354.             fu.Dispose();
  355.             return false;
  356.         }
  357.         #endregion
  358.         #region 方法 -- 创建新的文件名
  359.         /// &ltsummary>
  360.         /// 创建新的文件名
  361.         /// </summary>
  362.         /// &ltreturns></returns>
  363.         public string CreateFileName()
  364.         {
  365.             string guid = System.Guid.NewGuid().ToString().ToLower();
  366.             guid = guid.Replace("-""");
  367.             return DateTime.Now.ToString("yyyyMMddhhmmss") + guid.Substring(0, 4);
  368.         }
  369.         #endregion
  370.         #region 方法 -- 删除文件
  371.         /// &ltsummary>
  372.         /// 删除文件
  373.         /// </summary>
  374.         /// &ltparam name="filename"></param>
  375.         public static void DeleteFile(string filename)
  376.         {
  377.             string s = HttpContext.Current.Server.MapPath(filename);
  378.             if (File.Exists(s))
  379.             {
  380.                 try
  381.                 {
  382.                     File.Delete(s);
  383.                 }
  384.                 catch
  385.                 { }
  386.             }
  387.         }
  388.         #endregion
  389.         #region 方法 -- 生成缩略图
  390.         /**/
  391.         /// &ltsummary>
  392.         /// 生成缩略图
  393.         /// </summary>
  394.         /// &ltparam name="originalImagePath">源图路径(物理路径)</param>
  395.         /// &ltparam name="thumbnailPath">缩略图路径(物理路径)</param>
  396.         /// &ltparam name="width">缩略图宽度</param>
  397.         /// &ltparam name="height">缩略图高度</param>
  398.         /// &ltparam name="mode">生成缩略图的方式</param>   
  399.         public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
  400.         {
  401.             System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
  402.             int towidth = width;
  403.             int toheight = height;
  404.             int x = 0;
  405.             int y = 0;
  406.             int ow = originalImage.Width;
  407.             int oh = originalImage.Height;
  408.             if (ow < towidth && oh < toheight)
  409.             {
  410.                 originalImage.Save(thumbnailPath);
  411.             }
  412.             else
  413.             {
  414.                 switch (mode.ToUpper())
  415.                 {
  416.                     case "HW"://指定高宽缩放(可能变形)           
  417.                         break;
  418.                     case "W"://指定宽,高按比例             
  419.                         toheight = originalImage.Height * width / originalImage.Width;
  420.                         break;
  421.                     case "H"://指定高,宽按比例
  422.                         towidth = originalImage.Width * height / originalImage.Height;
  423.                         break;
  424.                     case "CUT"://指定高宽裁减(不变形)           
  425.                         if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
  426.                         {
  427.                             oh = originalImage.Height;
  428.                             ow = originalImage.Height * towidth / toheight;
  429.                             y = 0;
  430.                             x = (originalImage.Width - ow) / 2;
  431.                         }
  432.                         else
  433.                         {
  434.                             ow = originalImage.Width;
  435.                             oh = originalImage.Width * height / towidth;
  436.                             x = 0;
  437.                             y = (originalImage.Height - oh) / 2;
  438.                         }
  439.                         break;
  440.                     case "AUTO"//自动适应高度
  441.                         if (ow > oh)
  442.                         {
  443.                             //newwidth = 200;
  444.                             toheight = (int)((double)oh / (double)ow * (double)towidth);
  445.                         }
  446.                         else
  447.                         {
  448.                             //newheight = 200;
  449.                             towidth = (int)((double)ow / (double)oh * (double)toheight);
  450.                         }
  451.                         break;
  452.                     default:
  453.                         break;
  454.                 }
  455.                 //进行缩图
  456.                 Bitmap img = new Bitmap(towidth, toheight);
  457.                 img.SetResolution(72f, 72f);
  458.                 Graphics gdiobj = Graphics.FromImage(img);
  459.                 gdiobj.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  460.                 gdiobj.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  461.                 gdiobj.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  462.                 gdiobj.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
  463.                 gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0,
  464.                                 towidth, toheight);
  465.                 Rectangle destrect = new Rectangle(0, 0,
  466.                                 towidth, toheight);
  467.                 gdiobj.DrawImage(originalImage, destrect, 0, 0, ow,
  468.                                 oh, GraphicsUnit.Pixel);
  469.                 System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1);
  470.                 ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
  471.                 System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
  472.                 try
  473.                 {
  474.                     if (ici != null)
  475.                     {
  476.                         img.Save(thumbnailPath, ici, ep);
  477.                     }
  478.                     else
  479.                     {
  480.                         img.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
  481.                     }
  482.                 }
  483.                 catch (System.Exception e)
  484.                 {
  485.                     throw e;
  486.                 }
  487.                 finally
  488.                 {
  489.                     gdiobj.Dispose();
  490.                     img.Dispose();
  491.                 }
  492.             }
  493.             originalImage.Dispose();
  494.         }
  495.         private static System.Drawing.Imaging.ImageCodecInfo GetEncoderInfo(String mimeType)
  496.         {
  497.             int j;
  498.             System.Drawing.Imaging.ImageCodecInfo[] encoders;
  499.             encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
  500.             for (j = 0; j < encoders.Length; ++j)
  501.             {
  502.                 if (encoders[j].MimeType == mimeType)
  503.                     return encoders[j];
  504.             }
  505.             return null;
  506.         }
  507.         #endregion
  508.         
  509.         #region 方法 -- 在图片上增加文字水印
  510.         /**/
  511.         /// &ltsummary>
  512.         /// 在图片上增加文字水印
  513.         /// </summary>
  514.         /// &ltparam name="Path">原服务器图片路径</param>
  515.         /// &ltparam name="Path_sy">生成的带文字水印的图片路径</param>
  516.         protected void AddShuiYinWord(string Path, string Path_sy)
  517.         {
  518.             System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
  519.             System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  520.             g.DrawImage(image, 0, 0, image.Width, image.Height);
  521.             System.Drawing.Font f = new System.Drawing.Font("Verdana", 16);
  522.             System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Blue);
  523.             g.DrawString(_addText, f, b, 15, 15);
  524.             g.Dispose();
  525.             image.Save(Path_sy);
  526.             image.Dispose();
  527.         }
  528.         #endregion
  529.         #region 方法 -- 在图片上生成图片水印
  530.         /**/
  531.         /// &ltsummary>
  532.         /// 在图片上生成图片水印
  533.         /// </summary>
  534.         /// &ltparam name="Path">原服务器图片路径</param>
  535.         /// &ltparam name="Path_syp">生成的带图片水印的图片路径</param>
  536.         /// &ltparam name="Path_sypf">水印图片路径</param>
  537.         protected void AddShuiYinPic(string Path, string Path_syp, string Path_sypf)
  538.         {
  539.             System.Drawing.Image image = System.Drawing.Image.FromFile(Path);
  540.             System.Drawing.Image copyImage = System.Drawing.Image.FromFile(Path_sypf);
  541.             System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  542.             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);
  543.             g.Dispose();
  544.             image.Save(Path_syp);
  545.             image.Dispose();
  546.         }
  547.         #endregion
  548.     }
  549. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值