頭次在簡書寫東西挑社,有什么問題多指教陨界。
之前在做一個網(wǎng)站用戶上傳頭像(可裁剪)功能,整理成文痛阻,如下:
1菌瘪、選擇插件,引用JS
(1)選上傳圖片的插件:我用的是=> fileupload ,網(wǎng)上下載包里面會有很多文件阱当,這邊引用了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方法就是上傳完畢的回調(diào)函數(shù)
? ? ? ? ? ? //注意result要和jquery的ajax的data參數(shù)區(qū)分,這個對象包含了整個請求信息?
? ? ? ? ? ? //返回的數(shù)據(jù)在result.result中弊添,假設我們服務器返回了一個json對象?
? ? ? ? ? ? var res = data.result;
? ? ? ? ? ? if (res.Success) {
? ? ? ? ? ? ? //上傳好圖片只有做的一些操作
? ? ? ? ? ? ? ? ? ? ShowImg(res.ShowImage, result[1], result[2]);? ? ? //在截圖區(qū)顯示
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? else {
? ? ? ? ? ? ? ? $("#hidErr").val()
? ? ? ? ? ? ? ? alert(res.Message);
? ? ? ? ? ? }
? ? ? ? }
//移動要裁剪圖片的區(qū)域之后點保存的操作
$("#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录淡、后臺操作
傳好圖片保存,獲得截圖并保存
public JsonResult UploadThumbImg()
? ? ? ? {
? ? ? ? ? ? var CurrentContext = HttpContext;
? ? ? ? ? ? // 獲取文件流
? ? ? ? ? ? var files = CurrentContext.Request.Files;
? ? ? ? ? ? if (files.Count > 0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Stream stream = null;
? ? ? ? ? ? ? ? System.Drawing.Image originalImg = null;? //原圖?
? ? ? ? ? ? ? ? int minWidth = 94;? //最小寬度
? ? ? ? ? ? ? ? int minHeight = 94;? //最小高度
? ? ? ? ? ? ? ? int maxWidth = 300;? //最大寬度
? ? ? ? ? ? ? ? int maxHeight = 300;? //最大高度
? ? ? ? ? ? ? ? string imageOfSize = string.Empty;? //返回信息
? ? ? ? ? ? ? ? try
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? // 文件上傳后的保存路徑
? ? ? ? ? ? ? ? ? ? String pathOnServer = Path.Combine(StorageRoot);//StorageRoot 路徑油坝,我寫的是全局變量嫉戚,因為很多地方用到
? ? ? ? ? ? ? ? ? ? string filePath = pathOnServer + "/Users/" + userName.ToLower() + "/" + loginType + "/";
? ? ? ? ? ? ? ? ? ? string uploadFilePath = filePath;
? ? ? ? ? ? ? ? ? ? string ext = Path.GetExtension(files[0].FileName).ToLower();? //上傳文件的后綴(小寫)
? ? ? ? ? ? ? ? ? ? if (!Directory.Exists(filePath))
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? Directory.CreateDirectory(filePath);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? string fileName = Path.GetFileName(files[0].FileName);// 原始文件名稱
? ? ? ? ? ? ? ? ? ? string saveName = Guid.NewGuid().ToString() + ext; // 保存文件名稱
? ? ? ? ? ? ? ? ? ? string flag = "/temp" + DateTime.Now.ToFileTime() + ext;
? ? ? ? ? ? ? ? ? ? if (ext == ".jpg" || ext == ".png")
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? uploadFilePath += "\\" + flag;? //圖文件路徑
? ? ? ? ? ? ? ? ? ? ? ? stream = files[0].InputStream;
? ? ? ? ? ? ? ? ? ? ? ? originalImg = System.Drawing.Image.FromStream(stream);
? ? ? ? ? ? ? ? ? ? ? ? if (originalImg.Width >= minWidth && originalImg.Height >= minHeight)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? originalImg.Save(uploadFilePath);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? imageOfSize = "Temp" + "$" + originalImg.Width + "$" + originalImg.Height;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? return Json(new { Success = false, Message = "Image size must be larger than " + minWidth + "*" + minHeight }, JsonRequestBehavior.AllowGet);//圖片尺寸必須大于
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? ? ? return Json(new { Success = false, Message = "The image format should be .jpg or .png" }, JsonRequestBehavior.AllowGet);//請輸入正確圖片格式
? ? ? ? ? ? ? ? ? ? return Json(new { Success = true, FileName = fileName, SaveName = saveName, ShowImage = UrlBase + "/Users/" + userName.ToLower() + "/" + loginType + "/" + flag, ThumbImgPath = "/Users/" + userName.ToLower() + "/" + loginType + "/" + flag, ImageOfSize = imageOfSize });
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? finally
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? if (originalImg != null)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? originalImg.Dispose();
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? if (stream != null)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? stream.Close();
? ? ? ? ? ? ? ? ? ? ? ? stream.Dispose();
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? GC.Collect();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return Json(new { Success = false, Message = "Please select the file to upload!" }, JsonRequestBehavior.AllowGet);//請選擇要上傳的文件刨裆!
? ? ? ? ? ? }
? ? ? ? }
[HttpPost]
? ? ? ? public JsonResult UploadImg(string pointX, string pointY, string imgUrl, string maxVal)
? ? ? ? {
? ? ? ? ? ? //Bitmap bitmap = null;? //按截圖區(qū)域生成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、創(chuàng)建畫布
? ? ? ? ? ? ? ? ? ? ? ? //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;
? ? ? ? ? ? ? ? ? ? ? ? //將圖片路徑保存至數(shù)據(jù)庫
? ? ? ? ? ? ? ? ? ? ? ? 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
? ? ? ? ? ? {
? ? ? ? ? ? ? ? // 創(chuàng)建畫布
? ? ? ? ? ? ? ? newImage = new Bitmap(originalImage.Width, originalImage.Height);
? ? ? ? ? ? ? ? graphics = Graphics.FromImage(newImage);
? ? ? ? ? ? ? ? // 指定高質量帆啃、低速度呈現(xiàn)。
? ? ? ? ? ? ? ? graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
? ? ? ? ? ? ? ? // 指定高質量的雙三次插值法窍帝。執(zhí)行預篩選以確保高質量的收縮努潘。此模式可產(chǎn)生質量最高的轉換圖像。
? ? ? ? ? ? ? ? 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;
? ? ? ? }
上傳成功顯示到裁剪區(qū)
?裁剪保存成功疯坤,右上角是裁剪后的圖片
參考自:https://www.cnblogs.com/wifi/articles/2573131.html