当初说这个需求的时候,在网上找了一点资料,但是基本上感觉不符合项目中的需求。参照一些项目,和同事的改造,终于是像点样子了
截图大致截为3个像素,每个像素使用的地方也不同,考虑图片不会是很多,分别压缩保存下来。
根据截取的像素位置,对应的压缩成相应的图片:
首先需要下载Jcrop.js与uploadify.js 上传图片的插件和截图的插件
前台页面
<script src="~/Scripts/uploadify/jquery.uploadify-3.1.min.js"></script> <script src="~/Scripts/Jcrop/jquery.Jcrop.min.js"></script> <script src="~/Scripts/Comm_UploadJcrop.js"></script> <script type="text/javascript"> $(document).ready(function () { //上传图片 UploadImg("file_uploadImg", false, "LoadJcropImage",true); //加载当前头像 var currentHeader= $("#hf_CurrentUserHeader").val(); if (currentHeader.length > 0 && currentHeader != "/Images/defaultHeader.png") SetJcropImage(currentHeader.replace(/_JQ/,"_YS")); }) function LoadJcropImage (file, data, response) { var url = eval("(" + data + ")"); SetJcropImage(url); } </script> <div class="DivContainer"> <input type="hidden" value="@ViewBag.CurrentHeader" id="hf_CurrentUserHeader" /> <input type="file" name="file_uploadImg" id="file_uploadImg" /> <div class="DataNormalTable_SpanTip div_NoFileTip">请先上传图片</div> <div class="UploadImgContainer" style="display:none;"> <table cellpadding="0" cellspacing="0"> <tr> <td rowspan="2" valign="middle" align="center" class="MainLargeTd"> <div class="DivContainer"> <img id="preview_large" alt="500 X 500" /> </div> </td> <td align="center" height="160"> <div class="Header_Img headBoxStyle" style="overflow:hidden;"> <img id="preview_large3" style="100%; height:100%;" /> </div> </td> </tr> <tr> <td valign="top" align="center"> <div class="BigHeader_Img headBoxStyle" style="overflow:hidden;"> <img id="preview_large2" style="100%; height:100%;" /> </div> </td> </tr> </table> <div id="crop_operation"> <input type="hidden" name="x" id="x"> <input type="hidden" name="y" id="y"> <input type="hidden" name="w" id="w"> <input type="hidden" name="h" id="h"> <input type="hidden" name="imgsrc" id="imgsrc"> </div> </div> </div>
需要引用对应的js
Comm_UploadJcrop.js
//剪裁头像对象和宽高比例 var jcrop_api, boundx, boundy; //上传图片 //Id:上传控件Id //IsShowProgress:是否需要展示进度条 //SuccessFunc: 上传成功执行的方法 function UploadImg(Id, IsShowProgress, SuccessFunc,IsJcrop) { var uploadObj = $("#" + Id); var htmlstr = "<div class='upload_ShowFileProgress' id='" + Id + "-queue' " + (IsShowProgress ? "" : "style='display:none;'") + "></div>"; uploadObj.parent().append(htmlstr); var img_UploadUrl = IsJcrop ? "/Upload/UploadifyHeader" : "/Upload/UploadifyImg"; //Upload控制器中方法 uploadObj.uploadify({ //指定swf文件 'swf': '/Scripts/uploadify/uploadify.swf',//下载uploadify插件中的uploadify.swf //后台处理的页面 'uploader': img_UploadUrl, //进度条id 'queueID': Id + "-queue", //进度条显示完成后是否自动消失 'removeCompleted': false, //按钮相关 'buttonClass': 'btn_Upload', 'buttonText': '请选择图片', 'height': '31', 'width': '108', //在浏览窗口底部的文件类型下拉菜单中显示的文本 'fileTypeDesc': 'Image Files', //允许上传的文件后缀 'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp; *.jpeg; *.svg', //选择文件后自动上传 'auto': true, //设置为true将允许多文件上传 'multi': false, 'onUploadSuccess': function (file, data, response) { if (SuccessFunc != undefined && SuccessFunc != null && SuccessFunc.length > 0) { eval(SuccessFunc + "(file,data,response)"); } } }); } //上传文件 //Id:上传控件Id //IsShowProgress:是否需要展示进度条 //SuccessFunc: 上传成功执行的方法 function UploadFile(Id, IsShowProgress, SuccessFunc) { var uploadObj = $("#" + Id); var htmlstr = "<div class='upload_ShowFileProgress' id='" + Id + "-queue' " + (IsShowProgress ? "" : "style='display:none;'") + "></div>"; uploadObj.parent().append(htmlstr); uploadObj.uploadify({ //指定swf文件 'swf': '/Scripts/uploadify/uploadify.swf', //后台处理的页面 'uploader': '/Upload/Uploadify', //进度条id 'queueID': Id + "-queue", //进度条显示完成后是否自动消失 'removeCompleted': false, //按钮相关 'buttonClass': 'btn_Upload', 'buttonText': '请选择文件', 'height': '31', 'width': '108', //上传文件的类型 默认为所有文件 'All Files': '*.*', //在浏览窗口底部的文件类型下拉菜单中显示的文本 //'fileTypeDesc': 'Image Files', //允许上传的文件后缀 'fileTypeExts': '*.*', //选择文件后自动上传 'auto': false, //设置为true将允许多文件上传 'multi': true, 'onUploadSuccess': function (file, data, response) { if (SuccessFunc != undefined && SuccessFunc != null && SuccessFunc.length > 0) { eval(SuccessFunc + "(file,data,response)"); } } }); } //设定图片 function SetJcropImage(url) { $(".div_NoFileTip").hide(); $(".UploadImgContainer").show(); $("#preview_large").attr("src", url); $("#preview_large2").attr("src", url); $("#preview_large3").attr("src", url); $("#imgsrc").val(url); ErealizeJcrop(url); } //剪切图片 function ErealizeJcrop(url) { var $pcnt = $('#preview_large2').parent(), xsize = $pcnt.width(), ysize = $pcnt.height(); $('#preview_large').Jcrop({ onChange: updatePreview, onSelect: updatePreview, onSelect: updateCoords, aspectRatio: xsize / ysize }, function () { var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; jcrop_api = this; // $preview.appendTo(jcrop_api.ui.holder); }); //更换图片时重新加载图片 if (jcrop_api != undefined) jcrop_api.setImage(url); function updateCoords(c) { $('#x').val(c.x); $('#y').val(c.y); $('#w').val(c.w); $('#h').val(c.h); }; function updatePreview(c) { if (parseInt(c.w) > 0) { var rx = xsize / c.w; var ry = ysize / c.h; $("#preview_large2").css({ Math.round(rx * boundx) + 'px', height: Math.round(ry * boundy) + 'px', marginLeft: '-' + Math.round(rx * c.x) + 'px', marginTop: '-' + Math.round(ry * c.y) + 'px' }); $pcnt = $('#preview_large3').parent(), xsize2 = $pcnt.height(); ysize2 = $pcnt.height(); var rx2 = xsize2 / c.w; var ry2 = ysize2 / c.h; $("#preview_large3").css({ Math.round(rx2 * boundx) + 'px', height: Math.round(ry2 * boundy) + 'px', marginLeft: '-' + Math.round(rx2 * c.x) + 'px', marginTop: '-' + Math.round(ry2 * c.y) + 'px' }); } };
后台代码:
#region 判断文件夹是否存在,不存在则创建,返回文件夹路径 private void CheckFileExistsCreateNew(string filepath) { if (!Directory.Exists(Server.MapPath(filepath))) { Directory.CreateDirectory(Server.MapPath(filepath));//创建文件夹 } } #endregion #region 上传图片 //上传头像 [HttpPost] public JsonResult UploadifyHeader(HttpPostedFileBase fileData) { if (fileData != null) { try { // 文件上传后的保存路径 string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称 string fileExtension = Path.GetExtension(fileName); // 文件扩展名 string saveName =DateTime.Now.ToString("yyyyMMddHHmmssffff")+"_Y" + fileExtension; // 保存文件名称 string Url = "/Upload/" + CurrentUserInfo.Sys_RentCompany.CompanyKey + "/" + CurrentUserInfo.Comm_User.Id + "/UploadImg"; //在项目中创建一个Upload文件夹存放上传和截取的图片 CurrentUserInfo.Sys_RentCompany.CompanyKey 为session 保存的值 这里对应的文件夹的路径 自己可以定义 string ShowUrl = Url + "/" + saveName; string filePhysicalPath = Server.MapPath(ShowUrl); //当前登陆人文件夹 CheckFileExistsCreateNew(Url); fileData.SaveAs(filePhysicalPath); //压缩图片 string YsFileImg = ImgHandler.YsImg(ShowUrl, filePhysicalPath); return Json(YsFileImg); } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet); } } else { return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet); } } //上传头像 [HttpPost] public JsonResult UploadifyImg(HttpPostedFileBase fileData) { if (fileData != null) { try { // 文件上传后的保存路径 string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称 string fileExtension = Path.GetExtension(fileName); // 文件扩展名 string saveName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_Y" + fileExtension; // 保存文件名称 //string filed = "/Upload/" + saveName;//路经 string Url = "/Upload/" + CurrentUserInfo.Sys_RentCompany.CompanyKey + "/" + CurrentUserInfo.Comm_User.Id + "/UploadImg"; string ShowUrl = Url + "/" + saveName; string filePhysicalPath = Server.MapPath(ShowUrl); //当前登陆人文件夹 CheckFileExistsCreateNew(Url); fileData.SaveAs(filePhysicalPath); return Json(ShowUrl); } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet); } } else { return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet); } } //保存剪切的图片 [HttpPost] public JsonResult JcropImg(FormCollection colls) { JsonFormatResult result = new JsonFormatResult { IsSuccess = true, Message = "保存成功!" }; try { int x = int.Parse(colls["x"]); int y = int.Parse(colls["y"]); int w = int.Parse(colls["w"]); int h = int.Parse(colls["h"]); string imgsrc = colls["imgsrc"]; string Path = ImgHandler.CutAvatar(imgsrc, x, y, w, h); result.Data = Path; } catch (Exception e) { result.IsSuccess = false; result.Message = e.Message; } return Json(result); } #endregion
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; namespace CRM.Common { public class ImgHandler { /// <summary> /// 剪裁头像图片 /// </summary> /// <param name="pointX">X坐标</param> /// <param name="pointY">Y坐标</param> /// <param name="imgUrl">被截图图片地址</param> /// <param name="rlSize">截图矩形的大小</param> public static string CutAvatar(string imgUrl, int pointX = 0, int pointY = 0, int width = 0, int height = 0) { System.Drawing.Bitmap bitmap = null; //按截图区域生成Bitmap System.Drawing.Image thumbImg = null; //被截图 System.Drawing.Graphics gps = null; //存绘图对象 System.Drawing.Image finalImg = null; //最终图片 try { int finalWidth = 180; int finalHeight = 180; if (!string.IsNullOrEmpty(imgUrl)) { bitmap = new System.Drawing.Bitmap(width, height); thumbImg = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(imgUrl)); gps = System.Drawing.Graphics.FromImage(bitmap); //读到绘图对象 gps.DrawImage(thumbImg, new Rectangle(0, 0, width, height), new Rectangle(pointX, pointY, width, height), GraphicsUnit.Pixel); finalImg = GetThumbNailImage(bitmap, finalWidth, finalHeight); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = 80;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } string finalUrl = imgUrl.Replace("_YS", "_JQ"); string finalPath = HttpContext.Current.Server.MapPath(finalUrl); string finalPathDir = finalPath.Substring(0, finalPath.LastIndexOf("\")); if (!Directory.Exists(finalPathDir)) { Directory.CreateDirectory(finalPathDir); } if (jpegICIinfo != null) { finalImg.Save(finalPath, jpegICIinfo, ep); } else { finalImg.Save(finalPath); } return finalUrl; } return ""; } catch (Exception) { return ""; } finally { bitmap.Dispose(); thumbImg.Dispose(); gps.Dispose(); finalImg.Dispose(); GC.Collect(); } } /// <summary> /// 压缩图片 /// </summary> /// <param name="imgUrl"></param> /// <param name="File"></param> /// <returns></returns> public static string YsImg(string imgUrl, string File) { System.Drawing.Image image = System.Drawing.Image.FromFile(File); System.Drawing.Image finalImg = ImgHandler.GetThumbNailImage(image, 500, 500); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = 100;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } string finalUrl = imgUrl.Replace("_Y", "_YS"); string finalPath = HttpContext.Current.Server.MapPath(finalUrl); string finalPathDir = finalPath.Substring(0, finalPath.LastIndexOf("\")); if (!Directory.Exists(finalPathDir)) { Directory.CreateDirectory(finalPathDir); } if (jpegICIinfo != null) { finalImg.Save(finalPath, jpegICIinfo, ep); } else { finalImg.Save(finalPath); } return finalUrl; } ///<summary> /// 对给定的一个图片(Image对象)生成一个指定大小的缩略图。 ///</summary> ///<param name="originalImage">原始图片</param> ///<param name="thumMaxWidth">缩略图的宽度</param> ///<param name="thumMaxHeight">缩略图的高度</param> ///<returns>返回缩略图的Image对象</returns> public static Image GetThumbNailImage(Image originalImage, int thumMaxWidth, int thumMaxHeight) { Size thumRealSize = System.Drawing.Size.Empty; Image newImage = originalImage; Graphics graphics = null; try { thumRealSize = GetNewSize(thumMaxWidth, thumMaxHeight, originalImage.Width, originalImage.Height); newImage = new System.Drawing.Bitmap(thumRealSize.Width, thumRealSize.Height); graphics = Graphics.FromImage(newImage); graphics.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumRealSize.Width, thumRealSize.Height), new Rectangle(0, 0, originalImage.Width, originalImage.Height), GraphicsUnit.Pixel); } catch { } finally { if (graphics != null) { graphics.Dispose(); graphics = null; } } return newImage; } ///<summary> /// 获取一个图片按等比例缩小后的大小。 ///</summary> ///<param name="maxWidth">需要缩小到的宽度</param> ///<param name="maxHeight">需要缩小到的高度</param> ///<param name="imageOriginalWidth">图片的原始宽度</param> ///<param name="imageOriginalHeight">图片的原始高度</param> ///<returns>返回图片按等比例缩小后的实际大小</returns> public static System.Drawing.Size GetNewSize(int maxWidth, int maxHeight, int imageOriginalWidth, int imageOriginalHeight) { double w = 0.0; double h = 0.0; double sw = Convert.ToDouble(imageOriginalWidth); double sh = Convert.ToDouble(imageOriginalHeight); double mw = Convert.ToDouble(maxWidth); double mh = Convert.ToDouble(maxHeight); if (sw < mw && sh < mh) { w = sw; h = sh; } else if ((sw / sh) > (mw / mh)) { w = maxWidth; h = (w * sh) / sw; } else { h = maxHeight; w = (h * sw) / sh; } return new System.Drawing.Size(Convert.ToInt32(w), Convert.ToInt32(h)); } } }
照搬的代码肯定会有缺陷,可以根据需求修改成适合的项目