MVC 上傳圖片,裁剪頭像

頭次在簡書寫東西挑社,有什么問題多指教陨界。

之前在做一個網(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

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市拥峦,隨后出現(xiàn)的幾起案子贴膘,更是在濱河造成了極大的恐慌,老刑警劉巖略号,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異洋闽,居然都是意外死亡玄柠,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門诫舅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來羽利,“玉大人,你說我怎么就攤上這事刊懈≌饣。” “怎么了?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵虚汛,是天一觀的道長匾浪。 經(jīng)常有香客問我,道長卷哩,這世上最難降的妖魔是什么蛋辈? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮将谊,結果婚禮上冷溶,老公的妹妹穿的比我還像新娘。我一直安慰自己尊浓,他們只是感情好逞频,可當我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著栋齿,像睡著了一般苗胀。 火紅的嫁衣襯著肌膚如雪襟诸。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天柒巫,我揣著相機與錄音励堡,去河邊找鬼。 笑死堡掏,一個胖子當著我的面吹牛应结,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播泉唁,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼鹅龄,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了亭畜?” 一聲冷哼從身側響起扮休,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎拴鸵,沒想到半個月后玷坠,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡劲藐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年八堡,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片聘芜。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡兄渺,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出汰现,到底是詐尸還是另有隱情挂谍,我是刑警寧澤,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布瞎饲,位于F島的核電站口叙,受9級特大地震影響,放射性物質發(fā)生泄漏企软。R本人自食惡果不足惜庐扫,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望仗哨。 院中可真熱鬧形庭,春花似錦、人聲如沸厌漂。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽苇倡。三九已至富纸,卻和暖如春囤踩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背晓褪。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工堵漱, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人涣仿。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓勤庐,卻偏偏與公主長得像,于是被迫代替她去往敵國和親好港。 傳聞我的和親對象是個殘疾皇子愉镰,可洞房花燭夜當晚...
    茶點故事閱讀 44,914評論 2 355

推薦閱讀更多精彩內(nèi)容