MVC 上传图片,裁剪头像
头次写博客,有什么问题多指教。
最近在做一个网站用户上传头像(可裁剪)功能,整理成文,如下:
1、选择插件,引用JS
(1)选上传图片的插件:我用的是=> fileupload ,网上下载包里面会有很多文件,这边引用了3个文件(最重要的 jquery 记得引)
jquery.iframe-transport.js
jquery.ui.widget.js
jquery.fileupload.js
(2)截取图片 cutpic.js
2、写前台上传图片 AJAX 语句
<input type="file" id="fileupload" name="files[]" multiple style="position: absolute; opacity: 0; -ms-filter: 'alpha(opacity=0)'; font-size: 1px;direction: ltr;cursor: pointer;margin-left: -50px;width: 100px; direction: ltr; cursor: pointer;">
$(function () { $("#tripMsg").hide(); $("#removeMsgerror").hide(); $("#fileupload").fileupload({ url: "/FileUpload/UploadThumbImg",//后台操作路径 dataType: 'json', add: function (e, data) { $("#removeMsgerror").hide(); data.submit(); }, done: function (e, data) { //done方法就是上传完毕的回调函数 //注意result要和jquery的ajax的data参数区分,这个对象包含了整个请求信息 //返回的数据在result.result中,假设我们服务器返回了一个json对象 var res = data.result; if (res.Success) { //上传好图片只有做的一些操作 ShowImg(res.ShowImage, result[1], result[2]); //在截图区显示 } } else { $("#hidErr").val() alert(res.Message); } } //移动要裁剪图片的区域之后点保存的操作 $("#btnSave").click(function () { $.ajax({ type: "POST", url: "/FileUpload/UploadImg", data: { imgUrl: $('#hidImageUrl').val(), pointX: $("#x").val(), pointY: $("#y").val(), maxVal: $("#maxVal").val() }, success: function (msg) { if (msg.Success) { } else { alert(msg.ReturnData); } }, error: function (xhr, msg, e) { alert("error"); } }); }); }); function ShowImg(imagePath, imgWidth, imgHeight) { var imgPath = imagePath != "" ? imagePath : "!images/ef_pic.jpg"; var ic = new ImgCropper("bgDiv", "dragDiv", imgPath, imgWidth, imgHeight, null); }
3、后台操作
传好图片保存,获得截图并保存
1 public JsonResult UploadThumbImg() 2 { 3 var CurrentContext = HttpContext; 4 // 获取文件流 5 var files = CurrentContext.Request.Files; 6 7 if (files.Count > 0) 8 { 9 10 Stream stream = null; 11 System.Drawing.Image originalImg = null; //原图 12 int minWidth = 94; //最小宽度 13 int minHeight = 94; //最小高度 14 int maxWidth = 300; //最大宽度 15 int maxHeight = 300; //最大高度 16 string imageOfSize = string.Empty; //返回信息 17 try 18 { 19 // 文件上传后的保存路径 20 String pathOnServer = Path.Combine(StorageRoot);//StorageRoot 路径,我写的是全局变量,因为很多地方用到 21 string filePath = pathOnServer + "/Users/" + userName.ToLower() + "/" + loginType + "/"; 22 string uploadFilePath = filePath; 23 string ext = Path.GetExtension(files[0].FileName).ToLower(); //上传文件的后缀(小写) 24 25 if (!Directory.Exists(filePath)) 26 { 27 Directory.CreateDirectory(filePath); 28 } 29 string fileName = Path.GetFileName(files[0].FileName);// 原始文件名称 30 string saveName = Guid.NewGuid().ToString() + ext; // 保存文件名称 31 string flag = "/temp" + DateTime.Now.ToFileTime() + ext; 32 if (ext == ".jpg" || ext == ".png") 33 { 34 uploadFilePath += "\\" + flag; //图文件路径 35 36 stream = files[0].InputStream; 37 38 originalImg = System.Drawing.Image.FromStream(stream); 39 40 if (originalImg.Width >= minWidth && originalImg.Height >= minHeight) 41 { 42 originalImg.Save(uploadFilePath); 43 44 imageOfSize = "Temp" + "$" + originalImg.Width + "$" + originalImg.Height; 45 } 46 else 47 { 48 return Json(new { Success = false, Message = "Image size must be larger than " + minWidth + "*" + minHeight }, JsonRequestBehavior.AllowGet);//图片尺寸必须大于 49 } 50 } 51 else 52 return Json(new { Success = false, Message = "The image format should be .jpg or .png" }, JsonRequestBehavior.AllowGet);//请输入正确图片格式 53 return Json(new { Success = true, FileName = fileName, SaveName = saveName, ShowImage = UrlBase + "/Users/" + userName.ToLower() + "/" + loginType + "/" + flag, ThumbImgPath = "/Users/" + userName.ToLower() + "/" + loginType + "/" + flag, ImageOfSize = imageOfSize }); 54 } 55 catch (Exception ex) 56 { 57 return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet); 58 } 59 finally 60 { 61 if (originalImg != null) 62 { 63 originalImg.Dispose(); 64 } 65 66 if (stream != null) 67 { 68 stream.Close(); 69 stream.Dispose(); 70 } 71 72 73 GC.Collect(); 74 } 75 76 } 77 else 78 { 79 80 return Json(new { Success = false, Message = "Please select the file to upload!" }, JsonRequestBehavior.AllowGet);//请选择要上传的文件! 81 } 82 83 }
[HttpPost] public JsonResult UploadImg(string pointX, string pointY, string imgUrl, string maxVal) { //Bitmap bitmap = null; //按截图区域生成Bitmap Image thumbImg = null; //被截图 //Graphics gps = null; //存绘图对象 Image cutImage = null; Image finalImg = null; //最终图片 string savePath = string.Empty; string msg = string.Empty; string fileName = string.Empty; bool result=true; if (!string.IsNullOrEmpty(pointX) && !string.IsNullOrEmpty(pointY) && !string.IsNullOrEmpty(imgUrl)) { try { int finalWidth = 94; int finalHeight = 94; var userName = Request.Cookies["userName"].Value; var loginType = Request.Cookies["loginType"].Value; ClientSiteUser cMod = bll.GetClientUserById(userName); int X = Convert.ToInt32(pointX); int Y = Convert.ToInt32(pointY); string ext = System.IO.Path.GetExtension(imgUrl).ToLower(); //上传文件的后缀(小写) string pathOnServer = Path.Combine(StorageRoot); string documentUrl = "/Users/" + userName.ToLower() + "/" + loginType;//存放文件夹 string docStr = pathOnServer + documentUrl;//上传路径 if (!string.IsNullOrWhiteSpace(userName) && cMod != null) { //获取截图 1、创建画布 //bitmap = new System.Drawing.Bitmap(Convert.ToInt32(maxVal), Convert.ToInt32(maxVal)); thumbImg = System.Drawing.Image.FromFile(pathOnServer + imgUrl); //System.Drawing.Rectangle rl = new System.Drawing.Rectangle(Convert.ToInt32(pointX), Convert.ToInt32(pointY), Convert.ToInt32(maxVal), Convert.ToInt32(maxVal)); //得到截图矩形 //gps = System.Drawing.Graphics.FromImage(bitmap); //// 在指定位置并且按指定大小绘制指定的 Image 的指定部分,获得到截图 //gps.DrawImage(thumbImg, 0, 0, rl, System.Drawing.GraphicsUnit.Pixel); cutImage = GetCutImage(Convert.ToInt32(pointX), Convert.ToInt32(pointY), thumbImg, Convert.ToInt32(maxVal)); //截图等比例缩放得到最终图片 finalImg = GetThumbImage(cutImage, finalWidth, finalHeight); fileName = "/Img" + DateTime.Now.ToFileTime() + ext; savePath = docStr + fileName; if (!string.IsNullOrWhiteSpace(cMod.UrlOfAvatarPicture)) { FileDel(cMod.UrlOfAvatarPicture); } msg = UrlBase + documentUrl + fileName; cMod.UrlOfAvatarPicture = documentUrl + fileName; //将图片路径保存至数据库 if (bll.UpdateUrlOfAvatarPicture(cMod)) { if (!System.IO.Directory.Exists(docStr)) { System.IO.Directory.CreateDirectory(docStr); } finalImg.Save(savePath); } else result = false; //显示释放资源 //bitmap.Dispose(); thumbImg.Dispose(); //gps.Dispose(); cutImage.Dispose(); finalImg.Dispose(); GC.Collect(); FileDel(imgUrl); } } catch (Exception ex) { result = false; msg = ex.Message; } } return Json(new { Success = result,ReturnData=msg }); } ///<summary> /// 裁剪图片 ///</summary> ///<param name="originalImage">原始图片</param> ///<param name="thumMaxWidth">裁剪后需要显示的宽度</param> ///<param name="thumMaxHeight">裁剪后需要显示的高度</param> ///<returns>返回裁剪后的Image对象</returns> public static System.Drawing.Image GetThumbImage(Image originalImage, int thumMaxWidth, int thumMaxHeight) { Image newImage = originalImage; Graphics graphics = null; try { // 创建画布 newImage = new Bitmap(originalImage.Width, originalImage.Height); graphics = Graphics.FromImage(newImage); // 指定高质量、低速度呈现。 graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; // 用白色清空 graphics.Clear(System.Drawing.Color.Transparent); // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。 graphics.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumRealSize.Width, thumRealSize.Height), new System.Drawing.Rectangle(0, 0, originalImage.Width, originalImage.Height), System.Drawing.GraphicsUnit.Pixel); } catch { } finally { if (graphics != null) { //显示释放资源 graphics.Dispose(); graphics = null; } } return newImage; }
上传成功显示到裁剪区
裁剪保存成功,右上角是裁剪后的图片
参考自:https://www.cnblogs.com/wifi/articles/2573131.html