1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using AirWheel.Cycling.Domain;
- using AirWheel.Cycling.Common;
- using AirWheel.Cycling.Service.IService;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Net;
- using System.Configuration;
- using System.Collections;
- using AirWheel.Cycling.WebPage.Controllers;
- namespace AirWheel.Cycling.WebPage.Areas.ComManage.Controllers
- {
- /// <summary>
- /// 文件上传控制器
- /// add 作者: 季健国 QQ:181589805 by 2016-10-14
- /// </summary>
- public class UploadController : BaseController
- {
- #region 声明容器
- /// <summary>
- /// 文章管理
- /// </summary>
- IUploadManage UploadManage { get; set; }
- #endregion
- #region 公共变量
- #endregion
- #region 基本视图
- /// <summary>
- /// 加载首页
- /// </summary>
- [UserAuthorizeAttribute(ModuleAlias = "Upload", OperaAction = "View")]
- public ActionResult Index()
- {
- ViewBag.Search = base.keywords;
- return View(BindList());
- }
- /// <summary>
- /// 加载详情
- /// </summary>
- [UserAuthorizeAttribute(ModuleAlias = "Upload", OperaAction = "Detail")]
- public ActionResult Detail(string id)
- {
- var entity = this.UploadManage.Get(p => p.ID == id) ?? new COM_UPLOAD();
- return View(entity);
- }
- #endregion
- #region 公共方法
- /// <summary>
- /// 绑定列表数据
- /// </summary>
- private PageInfo<COM_UPLOAD> BindList()
- {
- var query = this.UploadManage.LoadAll(null);
- if (!string.IsNullOrEmpty(keywords))
- {
- query = query.Where(p => p.UPOLDNAME.Contains(keywords));
- }
- //除管理员,其他人默认看自己的文件
- if (!this.CurrentUser.IsAdmin)
- {
- var userid = CurrentUser.Id.ToString();
- query = query.Where(p => p.FK_USERID == userid);
- }
- query = query.OrderByDescending(p => p.UPTIME);
- return this.UploadManage.Query(query, base.page, base.pagesize);
- }
-
- #endregion
- #region 私有方法
- /// <summary>
- /// 返回上传目录相对路径
- /// </summary>
- /// <param name="fileName">上传文件名</param>
- private string GetUpLoadPath(bool isImg, string ext)
- {
- string path = ConfigurationManager.AppSettings["uppath"];
- if (isImg && IsImage(ext))
- {
- path += "images/";
- }
- else
- {
- path += "files/";
- }
- #region 用户控制
- //判读是否为超级管理员,超级管理员可查看所有的文件
- if (!base.CurrentUser.IsAdmin)
- {
- path += base.CurrentUser.LogName + "/";
- }
- #endregion
- path += DateTime.Now.ToString("yyyyMMdd") + "/";
- return path;
- }
- /// <summary>
- /// 是否为图片文件
- /// </summary>
- /// <param name="_fileExt">文件扩展名,不含“.”</param>
- private bool IsImage(string _fileExt)
- {
- ArrayList al = new ArrayList();
- al.Add("bmp");
- al.Add("jpeg");
- al.Add("jpg");
- al.Add("gif");
- al.Add("png");
- if (al.Contains(_fileExt.ToLower()))
- return true;
- return false;
- }
- /// <summary>
- /// 是否需要打水印
- /// </summary>
- /// <param name="_fileExt">文件扩展名,不含“.”</param>
- private bool IsWaterMark(string _fileExt)
- {
- //判断是否开启水印
- if (ConfigurationManager.AppSettings["watermarktype"].ToString() != "0")
- {
- //判断是否可以打水印的图片类型
- ArrayList al = new ArrayList();
- al.Add("bmp");
- al.Add("jpeg");
- al.Add("jpg");
- al.Add("png");
- if (al.Contains(_fileExt.ToLower()))
- {
- return true;
- }
- }
- return false;
- }
- /// <summary>
- /// 检查是否为合法的上传文件
- /// </summary>
- private bool CheckFileExt(string _fileExt)
- {
- //检查危险文件
- string[] excExt = { "asp", "aspx", "php", "jsp", "htm", "html" };
- for (int i = 0; i < excExt.Length; i++)
- {
- if (excExt[i].ToLower() == _fileExt.ToLower())
- {
- return false;
- }
- }
- //检查合法文件
- string[] allowExt = ConfigurationManager.AppSettings["attachextension"].ToString().Split(',');
- for (int i = 0; i < allowExt.Length; i++)
- {
- if (allowExt[i].ToLower() == _fileExt.ToLower())
- {
- return true;
- }
- }
- return false;
- }
- /// <summary>
- /// 检查文件大小是否合法
- /// </summary>
- /// <param name="_fileExt">文件扩展名,不含“.”</param>
- /// <param name="_fileSize">文件大小(B)</param>
- private bool CheckFileSize(string _fileExt, int _fileSize)
- {
- //判断是否为图片文件
- if (IsImage(_fileExt))
- {
- if (_fileSize > int.Parse(ConfigurationManager.AppSettings["attachimgsize"].ToString()) * 1024)
- return false;
- }
- else
- {
- if (_fileSize > int.Parse(ConfigurationManager.AppSettings["attachfilesize"].ToString()) * 1024)
- return false;
- }
- return true;
- }
- /// <summary>
- /// 是否真实,入侵验证
- /// </summary>
- /// <param name="_fileBinary">文件post</param>
- /// <param name="newfilePath">新文件路径+文件名</param>
- /// <returns></returns>
- private bool CheckFileTrue(HttpPostedFileBase _fileBinary, string newfilePath)
- {
- Stream fs = _fileBinary.InputStream;
- BinaryReader br = new BinaryReader(fs);
- byte but;
- string str = "";
- try
- {
- but = br.ReadByte();
- str = but.ToString();
- but = br.ReadByte();
- str += but.ToString();
- }
- catch
- {
- return false;
- }
- /*文件扩展名说明
- * 4946/104116 txt
- * 7173 gif
- * 255216 jpg
- * 13780 png
- * 6677 bmp
- * 239187 txt,aspx,asp,sql
- * 208207 xls.doc.ppt
- * 6063 xml
- * 6033 htm,html
- * 4742 js
- * 8075 xlsx,zip,pptx,mmap,zip
- * 8297 rar
- * 01 accdb,mdb
- * 7790 exe,dll
- * 5666 psd
- * 255254 rdp
- * 10056 bt种子
- * 64101 bat
- * 4059 sgf
- * 3780 pdf
- */
- bool bl = false;
- string[] binary = { "4946", "104116", "7173", "255216", "13780", "6677", "239187", "208207", "6063", "6033", "4742", "8075", "8297", "01", "5666", "255254", "10056" };
- for (int i = 0; i < binary.Length; i++)
- {
- if (binary[i].ToLower() == str.ToLower())
- {
- bl = true;
- }
- }
- if (bl)
- {
- _fileBinary.SaveAs(newfilePath);
- }
- br.Close();
- fs.Close();
- return bl;
- }
- /// <summary>
- /// 文件上传方法
- /// </summary>
- /// <param name="postedFile">文件流</param>
- /// <param name="isThumbnail">是否生成缩略图</param>
- /// <returns>上传后文件信息</returns>
- private JsonHelper FileSaveAs(HttpPostedFileBase postedFile, bool isThumbnail, bool isWater, bool isImg)
- {
- var jsons = new JsonHelper { Status = "n" };
- try
- {
- string fileExt = Utils.GetFileExt(postedFile.FileName); //文件扩展名,不含“.”
- int fileSize = postedFile.ContentLength; //获得文件大小,以字节为单位
- string fileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1); //取得原文件名
- string newFileName = Utils.GetRamCode() + "." + fileExt; //随机生成新的文件名
- string upLoadPath = GetUpLoadPath(isImg, fileExt); //上传目录相对路径
- string fullUpLoadPath = Utils.GetMapPath(upLoadPath); //上传目录的物理路径
- string newFilePath = upLoadPath + newFileName; //上传后的路径
- string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名
- //检查文件扩展名是否合法
- if (!CheckFileExt(fileExt))
- {
- jsons.Msg = "不允许上传" + fileExt + "类型的文件!";
- return jsons;
- }
- //检查文件大小是否合法
- if (!CheckFileSize(fileExt, fileSize))
- {
- jsons.Msg = "文件超过限制的大小啦!";
- return jsons;
- }
- //检查上传的物理路径是否存在,不存在则创建
- if (!Directory.Exists(fullUpLoadPath))
- {
- Directory.CreateDirectory(fullUpLoadPath);
- }
- //检查文件是否真实合法
- //if (!CheckFileTrue(postedFile, fullUpLoadPath + newFileName))
- //{
- // jsons.Msg = "不允许上传不可识别的文件!";
- // return jsons;
- //}
- postedFile.SaveAs(fullUpLoadPath + newFileName);
- string thumbnail = string.Empty;
- //如果是图片,检查是否需要生成缩略图,是则生成
- if (IsImage(fileExt) && isThumbnail && ConfigurationManager.AppSettings["thumbnailwidth"].ToString() != "0" && ConfigurationManager.AppSettings["thumbnailheight"].ToString() != "0")
- {
- Thumbnail.MakeThumbnailImage(fullUpLoadPath + newFileName, fullUpLoadPath + newThumbnailFileName,
- int.Parse(ConfigurationManager.AppSettings["thumbnailwidth"]), int.Parse(ConfigurationManager.AppSettings["thumbnailheight"]), "Cut");
- thumbnail = upLoadPath + newThumbnailFileName;
- }
- //如果是图片,检查是否需要打水印
- if (IsWaterMark(fileExt) && isWater)
- {
- switch (ConfigurationManager.AppSettings["watermarktype"].ToString())
- {
- case "1":
- WaterMark.AddImageSignText(newFilePath, newFilePath,
- ConfigurationManager.AppSettings["watermarktext"], int.Parse(ConfigurationManager.AppSettings["watermarkposition"]),
- int.Parse(ConfigurationManager.AppSettings["watermarkimgquality"]), ConfigurationManager.AppSettings["watermarkfont"], int.Parse(ConfigurationManager.AppSettings["watermarkfontsize"]));
- break;
- case "2":
- WaterMark.AddImageSignPic(newFilePath, newFilePath,
- ConfigurationManager.AppSettings["watermarkpic"], int.Parse(ConfigurationManager.AppSettings["watermarkposition"]),
- int.Parse(ConfigurationManager.AppSettings["watermarkimgquality"]), int.Parse(ConfigurationManager.AppSettings["watermarktransparency"]));
- break;
- }
- }
- string unit = string.Empty;
- //处理完毕,返回JOSN格式的文件信息
- jsons.Data = "{\"oldname\": \"" + fileName + "\","; //原始名称
- jsons.Data += " \"newname\":\"" + newFileName + "\","; //新名称
- jsons.Data += " \"path\": \"" + newFilePath + "\", "; //路径
- jsons.Data += " \"thumbpath\":\"" + thumbnail + "\","; //缩略图
- jsons.Data += " \"size\": \"" + fileSize + "\","; //大小
- jsons.Data += "\"ext\":\"" + fileExt + "\"}";//后缀名
- jsons.Status = "y";
- return jsons;
- }
- catch
- {
- jsons.Msg = "上传过程中发生意外错误!";
- return jsons;
- }
- }
- #endregion
- #region 其他调用
- /// <summary>
- /// 上传主调用器
- /// </summary>
- public ActionResult FileMain()
- {
- return View();
- }
- /// <summary>
- /// 图片预览视图
- /// </summary>
- public ActionResult Show()
- {
- return View();
- }
- /// <summary>
- /// 通过路径获取文件
- /// </summary>
- /// <returns></returns>
- public ActionResult GetFileData()
- {
- string path = Request.Form["path"];
- var jsonM = new JsonHelper() { Status = "y", Msg = "success" };
- try
- {
- jsonM.Data = Utils.DataTableToList<FileModel>(FileHelper.GetFileTable(Server.MapPath(path))).OrderByDescending(p => p.time).ToList();
- }
- catch (Exception ex)
- {
- jsonM.Status = "err";
- jsonM.Msg = "上传过程中发生错误,消息:" + ex.Message;
- }
- return Content(JsonConverter.Serialize(jsonM, true));
- }
- /// <summary>
- /// 单个文件上传
- /// </summary>
- [HttpPost]
- public ActionResult SignUpFile()
- {
- var jsonM = new JsonHelper() { Status = "n", Msg = "success" };
- try
- {
- HttpPostedFileBase upfile = Request.Files["fileUp"]; //取得上传文件
- var isImg = Request.QueryString["isImg"];
- string delpath = Request.QueryString["delpath"];
- if (upfile == null)
- {
- jsonM.Msg = "请选择要上传文件!";
- return Json(jsonM);
- }
- jsonM = FileSaveAs(upfile, false, false, (isImg.ToLower() == "true" ? true : false));
- #region 移除原始文件
- if (jsonM.Status == "y" && !string.IsNullOrEmpty(delpath))
- {
- if (System.IO.File.Exists(Utils.GetMapPath(delpath)))
- {
- System.IO.File.Delete(Utils.GetMapPath(delpath));
- }
- }
- #endregion
- if (jsonM.Status == "y")
- {
- #region 记录上传数据
- string unit = string.Empty;
- var jsonValue = JsonConverter.ConvertJson(jsonM.Data.ToString());
- var entity = new COM_UPLOAD()
- {
- ID = Guid.NewGuid().ToString(),
- FK_USERID = this.CurrentUser.Id.ToString(),
- UPOPEATOR = this.CurrentUser.Name,
- UPTIME = DateTime.Now,
- UPOLDNAME = jsonValue.oldname,
- UPNEWNAME = jsonValue.newname,
- UPFILESIZE = FileHelper.GetDiyFileSize(long.Parse(jsonValue.size), out unit),
- UPFILEUNIT = unit,
- UPFILEPATH = jsonValue.path,
- UPFILESUFFIX = jsonValue.ext,
- UPFILETHUMBNAIL = jsonValue.thumbpath,
- UPFILEIP = Utils.GetIP(),
- UPFILEURL = "http://" + Request.Url.AbsoluteUri.Replace("http://", "").Substring(0, Request.Url.AbsoluteUri.Replace("http://", "").IndexOf('/'))
- };
- this.UploadManage.Save(entity);
- #endregion
- #region 返回文件信息
- jsonM.Data = "{\"oldname\": \"" + jsonValue.oldname + "\","; //原始名称
- jsonM.Data += " \"newname\":\"" + jsonValue.newname + "\","; //新名称
- jsonM.Data += " \"path\": \"" + jsonValue.path + "\", "; //路径
- jsonM.Data += " \"thumbpath\":\"" + jsonValue.thumbpath + "\","; //缩略图
- jsonM.Data += " \"size\": \"" + jsonValue.size + "\","; //大小
- jsonM.Data += " \"id\": \"" + entity.ID + "\","; //上传文件ID
- jsonM.Data += " \"uptime\": \"" + entity.UPTIME + "\","; //上传时间
- jsonM.Data += " \"operator\": \"" + entity.UPOPEATOR + "\","; //上传人
- jsonM.Data += " \"unitsize\": \"" + entity.UPFILESIZE + unit + "\","; //带单位大小
- jsonM.Data += "\"ext\":\"" + jsonValue.ext + "\"}";//后缀名
- #endregion
- }
-
- }
- catch (Exception ex)
- {
- jsonM.Msg = "上传过程中发生错误,消息:" + ex.Message;
- jsonM.Status = "n";
- }
- return Json(jsonM);
- }
- /// <summary>
- /// 删除文件或文件夹
- /// </summary>
- /// <returns></returns>
- public ActionResult DeleteBy()
- {
- var jsonM = new JsonHelper() { Status = "y", Msg = "success" };
- try
- {
- var path = Request.QueryString["path"];
- var isFile = Request.QueryString["isfile"];
- if (isFile == "0")
- {
- //删除文件夹
- FileHelper.ClearDirectory(Server.MapPath(path));
- }
- else
- {
- //删除文件
- FileHelper.DeleteFile(Server.MapPath(path));
- }
- }
- catch (Exception ex)
- {
- jsonM.Status = "err";
- jsonM.Msg = "删除过程中发生错误,消息:" + ex.Message;
- }
- return Json(jsonM);
- }
- #endregion
- }
- #region 自定义类
- /// <summary>
- /// 文件模型
- /// </summary>
- public class FileModel
- {
- public string name { get; set; }
- public string ext { get; set; }
- public string size { get; set; }
- public DateTime time { get; set; }
- }
- /// <summary>
- /// 缩略图构造类
- /// </summary>
- public class Thumbnail
- {
- private Image srcImage;
- private string srcFileName;
- /// <summary>
- /// 创建
- /// </summary>
- /// <param name="FileName">原始图片路径</param>
- public bool SetImage(string FileName)
- {
- srcFileName = Utils.GetMapPath(FileName);
- try
- {
- srcImage = Image.FromFile(srcFileName);
- }
- catch
- {
- return false;
- }
- return true;
- }
- /// <summary>
- /// 回调
- /// </summary>
- /// <returns></returns>
- public bool ThumbnailCallback()
- {
- return false;
- }
- /// <summary>
- /// 生成缩略图,返回缩略图的Image对象
- /// </summary>
- /// <param name="Width">缩略图宽度</param>
- /// <param name="Height">缩略图高度</param>
- /// <returns>缩略图的Image对象</returns>
- public Image GetImage(int Width, int Height)
- {
- Image img;
- Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
- img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
- return img;
- }
- /// <summary>
- /// 保存缩略图
- /// </summary>
- /// <param name="Width"></param>
- /// <param name="Height"></param>
- public void SaveThumbnailImage(int Width, int Height)
- {
- switch (Path.GetExtension(srcFileName).ToLower())
- {
- case ".png":
- SaveImage(Width, Height, ImageFormat.Png);
- break;
- case ".gif":
- SaveImage(Width, Height, ImageFormat.Gif);
- break;
- default:
- SaveImage(Width, Height, ImageFormat.Jpeg);
- break;
- }
- }
- /// <summary>
- /// 生成缩略图并保存
- /// </summary>
- /// <param name="Width">缩略图的宽度</param>
- /// <param name="Height">缩略图的高度</param>
- /// <param name="imgformat">保存的图像格式</param>
- /// <returns>缩略图的Image对象</returns>
- public void SaveImage(int Width, int Height, ImageFormat imgformat)
- {
- if (imgformat != ImageFormat.Gif && (srcImage.Width > Width) || (srcImage.Height > Height))
- {
- Image img;
- Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
- img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
- srcImage.Dispose();
- img.Save(srcFileName, imgformat);
- img.Dispose();
- }
- }
- #region Helper
- /// <summary>
- /// 保存图片
- /// </summary>
- /// <param name="image">Image 对象</param>
- /// <param name="savePath">保存路径</param>
- /// <param name="ici">指定格式的编解码参数</param>
- private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
- {
- //设置 原图片 对象的 EncoderParameters 对象
- EncoderParameters parameters = new EncoderParameters(1);
- parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)100));
- image.Save(savePath, ici, parameters);
- parameters.Dispose();
- }
- /// <summary>
- /// 获取图像编码解码器的所有相关信息
- /// </summary>
- /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
- /// <returns>返回图像编码解码器的所有相关信息</returns>
- private static ImageCodecInfo GetCodecInfo(string mimeType)
- {
- ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
- foreach (ImageCodecInfo ici in CodecInfo)
- {
- if (ici.MimeType == mimeType)
- return ici;
- }
- return null;
- }
- /// <summary>
- /// 计算新尺寸
- /// </summary>
- /// <param name="width">原始宽度</param>
- /// <param name="height">原始高度</param>
- /// <param name="maxWidth">最大新宽度</param>
- /// <param name="maxHeight">最大新高度</param>
- /// <returns></returns>
- private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
- {
- //此次2012-02-05修改过=================
- if (maxWidth <= 0)
- maxWidth = width;
- if (maxHeight <= 0)
- maxHeight = height;
- //以上2012-02-05修改过=================
- decimal MAX_WIDTH = (decimal)maxWidth;
- decimal MAX_HEIGHT = (decimal)maxHeight;
- decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT;
- int newWidth, newHeight;
- decimal originalWidth = (decimal)width;
- decimal originalHeight = (decimal)height;
- if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
- {
- decimal factor;
- // determine the largest factor
- if (originalWidth / originalHeight > ASPECT_RATIO)
- {
- factor = originalWidth / MAX_WIDTH;
- newWidth = Convert.ToInt32(originalWidth / factor);
- newHeight = Convert.ToInt32(originalHeight / factor);
- }
- else
- {
- factor = originalHeight / MAX_HEIGHT;
- newWidth = Convert.ToInt32(originalWidth / factor);
- newHeight = Convert.ToInt32(originalHeight / factor);
- }
- }
- else
- {
- newWidth = width;
- newHeight = height;
- }
- return new Size(newWidth, newHeight);
- }
- /// <summary>
- /// 得到图片格式
- /// </summary>
- /// <param name="name">文件名称</param>
- /// <returns></returns>
- public static ImageFormat GetFormat(string name)
- {
- string ext = name.Substring(name.LastIndexOf(".") + 1);
- switch (ext.ToLower())
- {
- case "jpg":
- case "jpeg":
- return ImageFormat.Jpeg;
- case "bmp":
- return ImageFormat.Bmp;
- case "png":
- return ImageFormat.Png;
- case "gif":
- return ImageFormat.Gif;
- default:
- return ImageFormat.Jpeg;
- }
- }
- #endregion
- /// <summary>
- /// 制作小正方形
- /// </summary>
- /// <param name="image">图片对象</param>
- /// <param name="newFileName">新地址</param>
- /// <param name="newSize">长度或宽度</param>
- public static void MakeSquareImage(Image image, string newFileName, int newSize)
- {
- int i = 0;
- int width = image.Width;
- int height = image.Height;
- if (width > height)
- i = height;
- else
- i = width;
- Bitmap b = new Bitmap(newSize, newSize);
- try
- {
- Graphics g = Graphics.FromImage(b);
- //设置高质量插值法
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- //设置高质量,低速度呈现平滑程度
- g.SmoothingMode = SmoothingMode.AntiAlias;
- g.PixelOffsetMode = PixelOffsetMode.HighQuality;
- //清除整个绘图面并以透明背景色填充
- g.Clear(Color.Transparent);
- if (width < height)
- g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle(0, (height - width) / 2, width, width), GraphicsUnit.Pixel);
- else
- g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle((width - height) / 2, 0, height, height), GraphicsUnit.Pixel);
- SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
- }
- finally
- {
- image.Dispose();
- b.Dispose();
- }
- }
- /// <summary>
- /// 制作小正方形
- /// </summary>
- /// <param name="fileName">图片文件名</param>
- /// <param name="newFileName">新地址</param>
- /// <param name="newSize">长度或宽度</param>
- public static void MakeSquareImage(string fileName, string newFileName, int newSize)
- {
- MakeSquareImage(Image.FromFile(fileName), newFileName, newSize);
- }
- /// <summary>
- /// 制作远程小正方形
- /// </summary>
- /// <param name="url">图片url</param>
- /// <param name="newFileName">新地址</param>
- /// <param name="newSize">长度或宽度</param>
- public static void MakeRemoteSquareImage(string url, string newFileName, int newSize)
- {
- Stream stream = GetRemoteImage(url);
- if (stream == null)
- return;
- Image original = Image.FromStream(stream);
- stream.Close();
- MakeSquareImage(original, newFileName, newSize);
- }
- /// <summary>
- /// 制作缩略图
- /// </summary>
- /// <param name="original">图片对象</param>
- /// <param name="newFileName">新图路径</param>
- /// <param name="maxWidth">最大宽度</param>
- /// <param name="maxHeight">最大高度</param>
- public static void MakeThumbnailImage(Image original, string newFileName, int maxWidth, int maxHeight)
- {
- Size _newSize = ResizeImage(original.Width, original.Height, maxWidth, maxHeight);
- using (Image displayImage = new Bitmap(original, _newSize))
- {
- try
- {
- displayImage.Save(newFileName, original.RawFormat);
- }
- finally
- {
- original.Dispose();
- }
- }
- }
- /// <summary>
- /// 制作缩略图
- /// </summary>
- /// <param name="fileName">文件名</param>
- /// <param name="newFileName">新图路径</param>
- /// <param name="maxWidth">最大宽度</param>
- /// <param name="maxHeight">最大高度</param>
- public static void MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight)
- {
- //2012-02-05修改过,支持替换
- byte[] imageBytes = File.ReadAllBytes(fileName);
- Image img = Image.FromStream(new System.IO.MemoryStream(imageBytes));
- MakeThumbnailImage(img, newFileName, maxWidth, maxHeight);
- //原文
- //MakeThumbnailImage(Image.FromFile(fileName), newFileName, maxWidth, maxHeight);
- }
- #region 2012-2-19 新增生成图片缩略图方法
- /// <summary>
- /// 生成缩略图
- /// </summary>
- /// <param name="fileName">源图路径(绝对路径)</param>
- /// <param name="newFileName">缩略图路径(绝对路径)</param>
- /// <param name="width">缩略图宽度</param>
- /// <param name="height">缩略图高度</param>
- /// <param name="mode">生成缩略图的方式</param>
- public static void MakeThumbnailImage(string fileName, string newFileName, int width, int height, string mode)
- {
- Image originalImage = Image.FromFile(fileName);
- int towidth = width;
- int toheight = height;
- int x = 0;
- int y = 0;
- int ow = originalImage.Width;
- int oh = originalImage.Height;
- switch (mode)
- {
- 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;
- default:
- break;
- }
- //新建一个bmp图片
- Bitmap b = new Bitmap(towidth, toheight);
- try
- {
- //新建一个画板
- Graphics g = Graphics.FromImage(b);
- //设置高质量插值法
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- //设置高质量,低速度呈现平滑程度
- g.SmoothingMode = SmoothingMode.AntiAlias;
- g.PixelOffsetMode = PixelOffsetMode.HighQuality;
- //清空画布并以透明背景色填充
- g.Clear(Color.Transparent);
- //在指定位置并且按指定大小绘制原图片的指定部分
- g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel);
- SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
- }
- catch (System.Exception e)
- {
- throw e;
- }
- finally
- {
- originalImage.Dispose();
- b.Dispose();
- }
- }
- #endregion
- #region 2012-10-30 新增图片裁剪方法
- /// <summary>
- /// 裁剪图片并保存
- /// </summary>
- /// <param name="fileName">源图路径(绝对路径)</param>
- /// <param name="newFileName">缩略图路径(绝对路径)</param>
- /// <param name="maxWidth">缩略图宽度</param>
- /// <param name="maxHeight">缩略图高度</param>
- /// <param name="cropWidth">裁剪宽度</param>
- /// <param name="cropHeight">裁剪高度</param>
- /// <param name="X">X轴</param>
- /// <param name="Y">Y轴</param>
- public static bool MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight, int cropWidth, int cropHeight, int X, int Y)
- {
- byte[] imageBytes = File.ReadAllBytes(fileName);
- Image originalImage = Image.FromStream(new System.IO.MemoryStream(imageBytes));
- Bitmap b = new Bitmap(cropWidth, cropHeight);
- try
- {
- using (Graphics g = Graphics.FromImage(b))
- {
- //设置高质量插值法
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
- //设置高质量,低速度呈现平滑程度
- g.SmoothingMode = SmoothingMode.AntiAlias;
- g.PixelOffsetMode = PixelOffsetMode.HighQuality;
- //清空画布并以透明背景色填充
- g.Clear(Color.Transparent);
- //在指定位置并且按指定大小绘制原图片的指定部分
- g.DrawImage(originalImage, new Rectangle(0, 0, cropWidth, cropWidth), X, Y, cropWidth, cropHeight, GraphicsUnit.Pixel);
- Image displayImage = new Bitmap(b, maxWidth, maxHeight);
- SaveImage(displayImage, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
- return true;
- }
- }
- catch (System.Exception e)
- {
- throw e;
- }
- finally
- {
- originalImage.Dispose();
- b.Dispose();
- }
- }
- #endregion
- /// <summary>
- /// 制作远程缩略图
- /// </summary>
- /// <param name="url">图片URL</param>
- /// <param name="newFileName">新图路径</param>
- /// <param name="maxWidth">最大宽度</param>
- /// <param name="maxHeight">最大高度</param>
- public static void MakeRemoteThumbnailImage(string url, string newFileName, int maxWidth, int maxHeight)
- {
- Stream stream = GetRemoteImage(url);
- if (stream == null)
- return;
- Image original = Image.FromStream(stream);
- stream.Close();
- MakeThumbnailImage(original, newFileName, maxWidth, maxHeight);
- }
- /// <summary>
- /// 获取图片流
- /// </summary>
- /// <param name="url">图片URL</param>
- /// <returns></returns>
- private static Stream GetRemoteImage(string url)
- {
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
- request.Method = "GET";
- request.ContentLength = 0;
- request.Timeout = 20000;
- HttpWebResponse response = null;
- try
- {
- response = (HttpWebResponse)request.GetResponse();
- return response.GetResponseStream();
- }
- catch
- {
- return null;
- }
- }
- }
- /// <summary>
- /// 水印构造类
- /// </summary>
- public class WaterMark
- {
- /// <summary>
- /// 图片水印
- /// </summary>
- /// <param name="imgPath">服务器图片相对路径</param>
- /// <param name="filename">保存文件名</param>
- /// <param name="watermarkFilename">水印文件相对路径</param>
- /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param>
- /// <param name="quality">附加水印图片质量,0-100</param>
- /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
- public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
- {
- if (!File.Exists(Utils.GetMapPath(imgPath)))
- return;
- byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
- Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
- filename = Utils.GetMapPath(filename);
- if (watermarkFilename.StartsWith("/") == false)
- watermarkFilename = "/" + watermarkFilename;
- watermarkFilename = Utils.GetMapPath(watermarkFilename);
- if (!File.Exists(watermarkFilename))
- return;
- Graphics g = Graphics.FromImage(img);
- //设置高质量插值法
- //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
- //设置高质量,低速度呈现平滑程度
- //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
- Image watermark = new Bitmap(watermarkFilename);
- if (watermark.Height >= img.Height || watermark.Width >= img.Width)
- return;
- ImageAttributes imageAttributes = new ImageAttributes();
- ColorMap colorMap = new ColorMap();
- colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
- colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
- ColorMap[] remapTable = { colorMap };
- imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
- float transparency = 0.5F;
- if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
- transparency = (watermarkTransparency / 10.0F);
- float[][] colorMatrixElements = {
- new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
- new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
- new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
- new float[] {0.0f, 0.0f, 0.0f, transparency, 0.0f},
- new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
- };
- ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
- imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
- int xpos = 0;
- int ypos = 0;
- switch (watermarkStatus)
- {
- case 1:
- xpos = (int)(img.Width * (float).01);
- ypos = (int)(img.Height * (float).01);
- break;
- case 2:
- xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
- ypos = (int)(img.Height * (float).01);
- break;
- case 3:
- xpos = (int)((img.Width * (float).99) - (watermark.Width));
- ypos = (int)(img.Height * (float).01);
- break;
- case 4:
- xpos = (int)(img.Width * (float).01);
- ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
- break;
- case 5:
- xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
- ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
- break;
- case 6:
- xpos = (int)((img.Width * (float).99) - (watermark.Width));
- ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
- break;
- case 7:
- xpos = (int)(img.Width * (float).01);
- ypos = (int)((img.Height * (float).99) - watermark.Height);
- break;
- case 8:
- xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
- ypos = (int)((img.Height * (float).99) - watermark.Height);
- break;
- case 9:
- xpos = (int)((img.Width * (float).99) - (watermark.Width));
- ypos = (int)((img.Height * (float).99) - watermark.Height);
- break;
- }
- g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
- ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
- ImageCodecInfo ici = null;
- foreach (ImageCodecInfo codec in codecs)
- {
- if (codec.MimeType.IndexOf("jpeg") > -1)
- ici = codec;
- }
- EncoderParameters encoderParams = new EncoderParameters();
- long[] qualityParam = new long[1];
- if (quality < 0 || quality > 100)
- quality = 80;
- qualityParam[0] = quality;
- EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
- encoderParams.Param[0] = encoderParam;
- if (ici != null)
- img.Save(filename, ici, encoderParams);
- else
- img.Save(filename);
- g.Dispose();
- img.Dispose();
- watermark.Dispose();
- imageAttributes.Dispose();
- }
- /// <summary>
- /// 文字水印
- /// </summary>
- /// <param name="imgPath">服务器图片相对路径</param>
- /// <param name="filename">保存文件名</param>
- /// <param name="watermarkText">水印文字</param>
- /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param>
- /// <param name="quality">附加水印图片质量,0-100</param>
- /// <param name="fontname">字体</param>
- /// <param name="fontsize">字体大小</param>
- public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
- {
- byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
- Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
- filename = Utils.GetMapPath(filename);
- Graphics g = Graphics.FromImage(img);
- Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
- SizeF crSize;
- crSize = g.MeasureString(watermarkText, drawFont);
- float xpos = 0;
- float ypos = 0;
- switch (watermarkStatus)
- {
- case 1:
- xpos = (float)img.Width * (float).01;
- ypos = (float)img.Height * (float).01;
- break;
- case 2:
- xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
- ypos = (float)img.Height * (float).01;
- break;
- case 3:
- xpos = ((float)img.Width * (float).99) - crSize.Width;
- ypos = (float)img.Height * (float).01;
- break;
- case 4:
- xpos = (float)img.Width * (float).01;
- ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
- break;
- case 5:
- xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
- ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
- break;
- case 6:
- xpos = ((float)img.Width * (float).99) - crSize.Width;
- ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
- break;
- case 7:
- xpos = (float)img.Width * (float).01;
- ypos = ((float)img.Height * (float).99) - crSize.Height;
- break;
- case 8:
- xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
- ypos = ((float)img.Height * (float).99) - crSize.Height;
- break;
- case 9:
- xpos = ((float)img.Width * (float).99) - crSize.Width;
- ypos = ((float)img.Height * (float).99) - crSize.Height;
- break;
- }
- g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
- g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);
- ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
- ImageCodecInfo ici = null;
- foreach (ImageCodecInfo codec in codecs)
- {
- if (codec.MimeType.IndexOf("jpeg") > -1)
- ici = codec;
- }
- EncoderParameters encoderParams = new EncoderParameters();
- long[] qualityParam = new long[1];
- if (quality < 0 || quality > 100)
- quality = 80;
- qualityParam[0] = quality;
- EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
- encoderParams.Param[0] = encoderParam;
- if (ici != null)
- img.Save(filename, ici, encoderParams);
- else
- img.Save(filename);
- g.Dispose();
- img.Dispose();
- }
- }
- #endregion
- }
|