注意如下頁面代碼裏,每一個凝視差點兒都是講的一個有用而又強大有趣的技巧哦!!javascript
由於編寫在線編輯器的緣由。這個控件也又一次封裝了一下,爲了參照,原先的代碼也不刪除了。新封裝的就貼在後面吧。css
/* * 用到的幾個樣式 */ <style> /* 全兼容的圖像本身主動垂直居中的關鍵樣式哦^_^ */ .imgmid { display: inline-block; *display: inline; *zoom: 1; height: 100%; width: 1px; margin-left: -1px; vertical-align: middle; } /* 圖片等比自適應大小的css實現,僅僅要設定最大寬度最大高度就可以了。比用JS實現來的方便輕巧高效多了吧^_^ */ .autoSize { max-width: 360px; max-height: 240px; vertical-align: middle; } .activeImg { position: absolute; } /* 方塊狀的容器,僅僅顯示圓形區域的樣式哦^_^ */ .showImg { width: 100px; height: 100px; display: none; position: relative; overflow: hidden; float: left; border-radius: 50%; behavior: url(css/PIE.htc); float:left; clear:right; } </style> <form method="post" id="fmPhoto" target="hidFrame" enctype="multipart/form-data" action="ReciveUpload"> <div class="fmc"> /* 無刷新表單提交的關鍵——隱藏的iframe,表單的target指向這個隱藏的iframe */ <iframe id="hidFrame" name="hidFrame" style="display:none"></iframe> <div style="width: 360px; height: 240px; position: relative; float:left;"> <div style="width: 360px; height: 240px; position: relative; overflow: hidden; float: left; text-align:center;"> <img alt="圖片格式爲jpg,最大爲2M" id="imgPhoto" src="@srcPhoto" class="autoSize" /><span class="imgmid"></span>/*這個span就是圖片垂直居中的關鍵*/ </div> <img alt="" id="imgScroll" src="~/Images/img_scroll.png" style="z-index: 100; left: 0; top: 0; position: absolute;" /> </div> <div class="showImg"> <img alt="" id="imgShow" src="@srcPhoto" style="position: absolute;" /> </div> <div style="color:Gray;clear:left; margin-bottom:20px;">圖片格式爲jpg,圖片最大爲2M</div> /* 可以本身定義樣式的file控件。就是這麼簡單。本身定義一個div,而後裏面放一個佔滿大小的全透明file標籤。怎麼樣,崇拜我吧^_^ */ <div style ="border:1px solid gray;position:relative; width:100px; height:40px;line-height:40px; text-align:center; vertical-align:middle;font-size:18px;">請選擇圖像 <input type="file" id="fileUpload" name="ImageFile" style="position: absolute; width: 100%; height: 100%; filter: alpha(opacity=0); opacity: 0; top: 0; left: 0;" /> </div> <input type="hidden" id="ImgWidth" name="ImgWidth" /> <input type="hidden" id="ImgHeight" name="ImgHeight" /> <input type="hidden" id="ImgTop" name="ImgTop" /> <input type="hidden" id="ImgLeft" name="ImgLeft" /> </div> <div class="mb"> <input type="submit" class="lang-btn" id="btnSubmit" value="肯定" /> <a href="javascript:;" class="lang-btn lang-btn-huge lang-cancel mlw">取消</a> </div> </form> <script type="text/javascript"> //本身定義光標 //document.body.style.cursor = "url('http://bbb.com/images/cur.cur')"; function UploadCallBack(msg) { if (msg.indexOf("上傳圖片出錯") == -1) { // 圖片樣式清理(防止新載入的圖片受影響),再加上必須的樣式 $("#imgPhoto").removeAttr("width").removeAttr("height").removeAttr("style").removeClass("activeImg").addClass("autoSize").attr("src", msg); $("#imgShow").attr("src", msg); } else { alert("系統忙,請稍後再試!"); } } // 圖片縮放和移動的代碼,也是超簡單吧, // 相比網上那些封裝好的代碼控件。動不動就是幾本JS,複雜得要死,又難以維護。 // 我這個實現。算是一個貢獻吧,還有助於剛開始學習的人學習和開啓智慧^_^ $(function () { var img = $("#imgScroll"); var obj = $("#imgPhoto"); var isMove = false; var x = y = 0; img.on("click", function (event) { if (isMove) { isMove = false; obj.css("cursor", "default"); $(".showImg").hide(); } else { isMove = true; img.css("cursor", "move"); obj.attr("width", obj.width()).attr("height", obj.height()).removeClass("autoSize").addClass("activeImg").css({ top: obj.css("top"), left: obj.css("left") }); var left = obj.css("left") == "auto" ?html
0 : obj.css("left"); var top = obj.css("top") == "auto" ?java
0 : obj.css("top"); x = event.pageX - parseInt(left); y = event.pageY - parseInt(top); $("#imgShow").attr("width", obj.width()).attr("height", obj.height()).css({ top: obj.css("top") - 70, left: obj.css("left") - 130 }); $(".showImg").show(); } }).on("mouseout", function () { isMove = false; obj.css("cursor", "default"); $(".showImg").hide(); }).on("mousewheel", function (event) { var wm = event.originalEvent.wheelDelta > 0 ? 1 : -1; var width = obj.width() * (10 + wm) / 10;//可適合改動 var height = obj.height() * (10 + wm) / 10; if (width > 100 && height > 100) { obj.width(width).css({ "left": (180 - (width / 2)) }); obj.height(height).css({ "top": (120 - (height / 2)) }); $("#imgShow").width(width).height(height).css({ top: 50 - (height / 2), left: 50 - (width / 2) }); $(".showImg").show(); } }); $(document).mousemove(function (e) { if (isMove) { obj.css({ top: e.pageY - y, left: e.pageX - x }); $("#imgShow").css({ top: e.pageY - y - 70, left: e.pageX - x - 130 }); } }); // file控件響應事件 $("#fileUpload").change(function () { var tmp = this.value.split('\\'); var fileName = tmp[tmp.length - 1].split('.'); document.forms["fmPhoto"].submit(); }); // 表單驗證和ajax提交, var valid = $("#fmPhoto").validate({ submitHandler: function () { $("#ImgWidth").val(obj.width()); $("#ImgHeight").val(obj.height()); $("#ImgTop").val(70 - parseInt(obj.css("top"), 10)); $("#ImgLeft").val(130 - parseInt(obj.css("left"), 10)); $.ajax({ url: "http://localhost:22397/Home/Photo", cache: false, type: "post", data: $("#fmPhoto").serialize(), success: function (result) { if (!result) { var errormap = { SystemMsg: "系統忙,請稍後再試。" }; valid.showErrors(errormap, valid.errorlist); } else { if (result.Msg) { valid.showErrors(result.Msg.Map, valid.errorlist); } else { $("#imgUserPhoto").attr("src", result.VirtualPath + result.Name); } } } }); }, rules: { Name: { required: true, } } }); }); </script> ajax
又一次封裝的js代碼:app
$(function () { window.Photo || (window.Photo = { x: 0, y: 0, w: 0, h: 0, l: 0, t: 0, mousedown: 0, html: '<form method="post" id="PhotoForm" target="hidFrame" enctype="multipart/form-data" action="{action}" style="width:600px;margin:0px auto;position:relative;">' + '<iframe id="hidFrame" name="hidFrame" style="display:none"></iframe>' + ' <div style="width: 480px; height: 360px; position: relative; float: left; overflow: hidden;">' + ' <img id="imgPhoto" src="{img}" onerror="this.src =\'../../Images/Account/DefaultPhoto.png\'" style="position:relative;" />' + ' <div id="cover" style="width: 800px;height: 800px;z-index: 100;position: absolute;border: 350px solid rgba(48, 168, 48, 0.5);border-bottom-left-radius: 50%;border-bottom-right-radius: 50%;border-top-left-radius: 50%;border-top-right-radius: 50%;top: -220px;left: -160px;"></div>' + ' </div>' + ' <div id="showImage" style="width: 100px;height: 100px;display: none;position: relative;overflow: hidden;float: left;border-radius: 50%;">' + ' <img alt="" id="imgShow" src="{img}" onerror="this.src=\'../../Images/Account/DefaultPhoto.png\'" style="position: relative;" />' + ' </div>' + ' <div style="color:Gray;clear:left; margin-bottom:20px;">圖片格式爲jpg。圖片最大爲2M</div>' + ' <div style="border:1px solid gray;position:relative; width:100px; height:40px;line-height:40px; text-align:center; vertical-align:middle;font-size:18px;display:inline-block;">' + ' 請選擇圖像' + ' <input type="file" id="fileUpload" name="ImageFile" style="position: absolute; width: 100%; height: 100%; filter: alpha(opacity=0); opacity: 0; top: 0; left: 0;" />' + ' </div>' + ' <a href="#" style="width:60px;height:30px; margin:10px 0 0 238px;">Cancel</a>' + ' <input type="button" style="width:60px;height:30px; margin:10px 0 0 30px;" id="btnSubmit" value="Save" />' + ' <input type="hidden" id="CallBcakFunction" name="CallBcakFunction" value="window.parent.Photo.UploadCallBack" />' + ' <input type="hidden" id="ImgWidth" name="width" />' + ' <input type="hidden" id="ImgHeight" name="height" />' + ' <input type="hidden" id="ImgTop" name="top" />' + ' <input type="hidden" id="ImgLeft" name="left" />' + '</form>', UploadCallBack: function (msg) { if (msg.indexOf("上傳圖片出錯") != -1) { alert("系統忙,請稍後再試!"); } else { Photo.image.attr('src', msg); } }, show: function (containner,action,saveurl,img) { Photo.Content = Photo.Content ? Photo.Content : $(Photo.html.replace('{action}', action).replace('{img}', img)).appendTo($(containner)); Photo.view = $("#imgShow"), Photo.image = $("#imgPhoto"), Photo.cover = $("#cover"), Photo.watch = $("#showImage"); $("#fileUpload").change(function () { var tmp = this.value.split('\\'); var fileName = tmp[tmp.length - 1].split('.'); Photo.Content.submit(); }); $("#btnSubmit").on('click', function () { $("#ImgTop").val(parseInt(130 - Photo.t, 10)); $("#ImgLeft").val(parseInt(190 - Photo.l, 10)); $("#ImgWidth").val(parseInt(Photo.w, 10)); $("#ImgHeight").val(parseInt(Photo.h, 10)); $.ajax({ url: saveurl, cache: false, type: "post", data: $("#PhotoForm").serialize(), success: function (result) { if (!result) { var errormap = { SystemMsg: "系統忙,請稍後再試。" }; valid.showErrors(errormap, valid.errorlist); } else { if (result.Msg) { valid.showErrors(result.Msg.Map, valid.errorlist); } else { $("#imgUserPhoto").attr("src", result.VirtualPath + result.Name); } } } }); }); $(document).mousemove(function (e) { if (Photo.mousedown) { Photo.t += e.pageY - Photo.y; Photo.l += e.pageX - Photo.x; Photo.image.css({ top: Photo.t, left: Photo.l }); Photo.view.css({ top: Photo.t - 130, left: Photo.l - 190 }); Photo.x = e.pageX; Photo.y = e.pageY; } }); Photo.image.on("load", function (e) { var img = new Image(); img.src = this.src; var ow = img.width, oh = img.height, b = 3 * Photo.w > 4 * Photo.h; Photo.w = b ? 480 : (ow * 360 / oh); Photo.h = b ?(oh * 480 / ow) : 360; Photo.l = (480 - Photo.w) / 2, Photo.t = (360 - Photo.h) / 2; Photo.image.css({ width: Photo.w, height: Photo.h, top: Photo.t, left: Photo.l }); Photo.view.css({ width: Photo.w, height: Photo.h, top: Photo.t - 130, left: Photo.l - 190 }).attr('src', this.src); }); Photo.cover.on("mousedown", function (e) { e.stopPropagation(); Photo.mousedown = true; Photo.cover.css("cursor", "move"); Photo.watch.show(); Photo.x = e.pageX; Photo.y = e.pageY; }).on("mouseup", function (e) { e.stopPropagation(); Photo.mousedown = false; Photo.cover.css("cursor", "default"); Photo.watch.hide(); }).on("mousewheel", function (e) { e.stopPropagation(); var wm = e.originalEvent.wheelDelta > 0 ? 1 : -1; nw = Photo.w * (10 + wm) / 10;//可適當改動 nh = Photo.h * (10 + wm) / 10; if (nw > 100 && nh > 100) { Photo.l = Photo.l + (Photo.w - nw) / 2; Photo.t = Photo.t + (Photo.h - nh) / 2; Photo.w = nw; Photo.h = nh; Photo.image.css({ width: Photo.w, height: Photo.h, top: Photo.t, left: Photo.l }); Photo.view.css({ width: Photo.w, height: Photo.h, top: Photo.t - 130, left: Photo.l - 190 }); } }); } }); Photo.show($('#customPhoto'), 'ReciveUpload', 'http://localhost:7427/Home/Photo', '@Model.xPhoto'); });編輯器
後臺的相關方法也放這吧,有需要的可以直接拿去用ide
public ActionResult Photo() { var guid = Cookies.ReadCookie("UserGuid"); var account = DAL.xV_Account.GetAccountByCode(Guid.Parse(guid)); Session["account"] = account; return View(account); } [HttpPost] public JsonResult Photo(int width,int height,int left,int top) { var account = Session["account"] as DAL.xV_Account; var p = Session["tmpImage"] as string; if (!string.IsNullOrWhiteSpace(p)) { ImageHelper.CutImage(Image.FromFile(p), width, height, left, top, 100, 100, p, account.xAccountCode); account.xPhoto = "http://" + Request.Url.Authority + "/Images/Photos/" + account.xAccountCode + ".jpg"; DAL.xV_Account.UpdatePhoto(account); } return Json(account); } /// <summary> /// 接收頁面無刷新提交的文檔(本例爲圖片)。並保存在暫時文件夾中,用Session記錄文件夾 /// </summary> /// <returns></returns> public ActionResult ReciveUpload() { string result = "<script type='text/javascript'>" + Request["CallBcakFunction"] + "('"; try { var account = Session["account"] as DAL.xV_Account; var p = Session["tmpImage"] as string; string fileName = Request.Files[0].FileName.Substring(Request.Files[0].FileName.LastIndexOf('\\') + 1); if (p == null) { p = "D:\\WorkSpace\\Project\\Viva\\Viva\\Images\\Photos\\" + account.xAccountCode + ".jpg"; } Session["tmpImage"] = p; //保存原圖 ImageHelper.SaveImage(Request.Files[0], p.Substring(0, p.LastIndexOf('\\')), account.xAccountCode + ".jpg", new string[] { "jpg","jpeg" }, 5); //返回保存的縮略圖的路徑 result += "http://" + Request.Url.Authority + "/Images/Photos/" + account.xAccountCode + ".jpg"; } catch { result += "上傳圖片出錯!請稍後再試,或尋求管理員的幫助."; } return Content(result + "');</script>"); } public static bool CutImage(Image image, int sWidth, int sHeight, int left, int top, int width, int height, string path, string name) { //用指定的大小和格式初始化 Bitmap 類的新實例 var bitmap = new Bitmap(sWidth, sHeight, PixelFormat.Format32bppArgb); //從指定的 Image 對象建立新 Graphics 對象 var graphics = Graphics.FromImage(bitmap); //清除整個畫圖面並以透明背景色填充 graphics.Clear(Color.Transparent); //在指定位置並且按指定大小繪製 原圖片 對象 graphics.DrawImage(image, new Rectangle(0, 0, sWidth, sHeight)); graphics.Dispose(); // 目標區域 var destRect = new Rectangle(0, 0, width, height); // 源圖區域 var srcRect = new Rectangle(left, top, width, height); // 新建Graphics對象 var newImage = new Bitmap(width, height); var g = Graphics.FromImage(newImage); // 畫圖平滑程序 g.SmoothingMode = SmoothingMode.HighQuality; // 圖片輸出質量 g.CompositingQuality = CompositingQuality.HighQuality; // 輸出到newImage對象 g.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel); // 釋放畫圖對象 g.Dispose(); // 保存圖像 if (File.Exists(path + name)) { File.Delete(path + name); } newImage.Save(path + name); return true; }post