當初說這個需求的時候,在網上找了一點資料,但是基本上感覺不符合項目中的需求。參照一些項目,和同事的改造,終於是像點樣子了
截圖大致截為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="width: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="width: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({ width: 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({ width: 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)); } } }
照搬的代碼肯定會有缺陷,可以根據需求修改成適合的項目