界面一: <link href="../theme/js/layui.layim/src/css/layui.css" rel="stylesheet"/> <style> #form1 { padding: 10px; } .usericon { margin-left: 0; } </style ...
界面一:
<link href="../theme/js/layui.layim/src/css/layui.css" rel="stylesheet"/> <style> #form1 { padding: 10px; } .usericon { margin-left: 0; } </style> <form class="layui-form" id="form1" runat="server"> <div class="layui-form-item"> <div class="layui-inline"> <label class="layui-form-label">上傳圖片</label> <div class="layui-input-block"> <button id="btnUpload" class="layui-btn" type="button">上傳</button> </div> </div> <div class="layui-inline"> <div class="layui-input-block usericon"> <img id="imgShow" src="../theme/img/user.jpg" onerror="../theme/img/user.jpg" width="150" height="150" /> </div> </div> </div> </form>頁面佈局代碼
<script src="../theme/js/layui.layim/src/layui.js"></script> <script src="../theme/js/jquery.min.js"></script> <script type="text/javascript"> layui.use(['layer'], function () { //上傳 $("#btnUpload").on("click", function () { layer.open({ title: ['上傳', 'font-size:18px;'], area: ['700px', '550px'], fixed: false, //不固定 maxmin: true, type: 2, content: "/test/PreviewImg.aspx" }); }); }); function Update(src) { $("#imgShow").attr("src", src); } </script>加入js腳本-點擊上傳彈出頁面進行頭像上傳和截圖,完成後調用Update方法刷新頁面
界面二:
<link href="../theme/js/layui.layim/src/css/layui.css" rel="stylesheet" /> <link href="../theme/js/Jcrop/css/jquery.Jcrop.min.css" rel="stylesheet" /> <style> .container { margin-right: auto; margin-left: auto; *zoom: 1; } .container:before, .container:after { display: table; content: ""; line-height: 0; } .container:after { clear: both; } .row { *zoom: 1; } .row:before, .row:after { display: table; content: ""; line-height: 0; } .row:after { clear: both; } .span12 { margin-left: 10px; margin-right: 10px; } .span12 .layui-btn{margin-left:10px;} .jc-demo-box { text-align: left; margin: 2em auto; background: white; border: 1px #bbb solid; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.25); -moz-box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.25); box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.25); padding: 1em 2em 2em; } form { margin: 1.5em 0; } .jcrop-holder #preview-pane { display: block; position: absolute; z-index: 2000; top: 10px; right: -280px; padding: 6px; border: 1px rgba(0,0,0,.4) solid; background-color: white; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2); -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2); box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2); } #preview-pane .preview-container { width: 250px; height: 250px; overflow: hidden; } </style> <form id="form1" runat="server"> <div class="container"> <div class="row"> <div class="span12"> <div class="jc-demo-box"> <img src="../theme/img/user.jpg" id="target" alt="[Jcrop Example]" /> <div id="preview-pane"> <div class="preview-container"> <img src="../theme/img/user.jpg" class="jcrop-preview" alt="Preview" /> </div> </div> </div> <button id="btnUpload" class="layui-btn" type="button">上傳</button> <button id="btnOk" class="layui-btn layui-btn-disabled" type="button">確定</button> <button id="btnX" class="layui-btn" type="button">0</button> <button id="btnY" class="layui-btn" type="button">0</button> <button id="btnW" class="layui-btn" type="button">0</button> <button id="btnH" class="layui-btn" type="button">0</button> </div> </div> </div> <asp:HiddenField ID="x1" runat="server" /> <asp:HiddenField ID="y1" runat="server" /> <asp:HiddenField ID="w" runat="server" /> <asp:HiddenField ID="h" runat="server" /> </form>頁面佈局代碼
<script src="../theme/js/jquery.min.js"></script> <script src="../theme/js/Jcrop/js/jquery.Jcrop.min.js"></script> <script src="../theme/js/layui.layim/src/layui.js"></script>
jQuery(function ($) { // Create variables (in this scope) to hold the API and image size var jcrop_api, boundx, boundy, // Grab some information about the preview pane $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'), xsize = $pcnt.width(), ysize = $pcnt.height(); //console.log('init', [xsize, ysize]); $('#target').Jcrop({ onChange: updatePreview, onSelect: updatePreview, aspectRatio: xsize / ysize }, function () { // Use the API to get the real image size var bounds = this.getBounds(); boundx = bounds[0]; boundy = bounds[1]; // Store the API in the jcrop_api variable jcrop_api = this; // Move the preview into the jcrop container for css positioning $preview.appendTo(jcrop_api.ui.holder); }); function updatePreview(c) { if (parseInt(c.w) > 0) { var rx = xsize / c.w; var ry = ysize / c.h; $pimg.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' }); } $('#x1').val(c.x);//左頂點的x坐標 $('#y1').val(c.y);//右頂點的x坐標 $('#w').val(c.w);//截圖的寬度 $('#h').val(c.h);//截圖的高度 $('#btnX').html(c.x);//左頂點的x坐標 $('#btnY').html(c.y);//右頂點的x坐標 $('#btnW').html(c.w);//截圖的寬度 $('#btnH').html(c.h);//截圖的高度 }; });js裁剪的腳本
//上傳文件 layui.use('upload', function () { var upload = layui.upload; //單個文件上傳 var uploadInst = upload.render({ elem: '#btnUpload' //綁定元素 , url: '/test/ashx/ashx.ashx' //上傳介面 , data: { action: "uploadimg" //, maxSize: $(".jcrop-holder>.jcrop-tracker").width() } , before: function (obj) {//在 choose 回調之後、done/error 回調之前觸發 //layer.load(); //上傳loading } , done: function (res) { //上傳完畢回調 $("#target").attr("src", res.data.src); $(".jcrop-holder>img").attr("src", res.data.src); $(".preview-container>img.jcrop-preview").attr("src", res.data.src); $(".jcrop-tracker").siblings("img").attr("src", res.data.src); //上傳圖片後-確定按鈕可用 $("#btnOk").removeClass("layui-btn-disabled"); } , error: function () { //請求異常回調 } }); });上傳文件
//確定 $("#btnOk").on("click", function () { if (!$(this).hasClass("layui-btn-disabled")) { var x= $('#x1').val();//左頂點的x坐標 var y = $('#y1').val();//右頂點的x坐標 var w = $('#w').val();//截圖的寬度 var h = $('#h').val();//截圖的高度 $.ajax({ //提交數據的類型 POST GET type: "POST", //提交的網址 url: '/test/ashx/ashx.ashx', //提交的數據 data: { action: "cutimg", x: x, y: y, w: w, h: h, src: $("#target").attr("src"), maxWidth: $(".jcrop-holder>.jcrop-tracker").width(), maxHeight: $(".jcrop-holder>.jcrop-tracker").height() }, //返回數據的格式-"xml", "html", "script", "json", "jsonp", "text". datatype: "json", //成功返回之後調用的函數 success: function (data) { if (data.code == 0) { parent.Update(data.src); CloseThis(); } }, //調用出錯執行的函數 error: function () { //請求出錯處理 } }); } }); //關閉當前iframe function CloseThis() { //先得到當前iframe層的索引 var index = parent.layer.getFrameIndex(window.name); parent.layer.close(index); //再執行關閉 }確定
/// <summary> /// 上傳圖片(如果沒有傳入寬高,不壓縮圖片) /// </summary> /// <param name="context"></param> /// <returns></returns> private string Uploadimg(HttpContext context) { int maxSize = 0;//壓縮後的最大尺寸(長或高,單位px) int.TryParse(context.Request.Params["maxSize"], out maxSize); //圖片保存路徑 string savePath = "/uploadfiles/test/" + DateTime.Now.ToString("yyyyMM") + "/"; if (!Directory.Exists(context.Server.MapPath(savePath))) { Directory.CreateDirectory(context.Server.MapPath(savePath)); } string fileName = Guid.NewGuid().ToString("N"); HttpPostedFile file = context.Request.Files[0];//上傳的圖片 if (file != null) {//上傳的圖片不為空 string fileExt = Path.GetExtension(file.FileName);//文件擴展名 fileName += fileExt; //壓縮後的圖片 Bitmap img = FileExt.ImageZip(file.InputStream, fileExt, maxSize); if (img != null) {//壓縮後的圖片不為空 img.Save(context.Server.MapPath(savePath + fileName)); } else {//原圖片保存 file.SaveAs(context.Server.MapPath(savePath + fileName)); } } return "{\"code\":0,\"msg\":\"上傳成功\",\"data\":{\"src\":\"" + (savePath + fileName) + "\"}}"; }執行後臺代碼-上傳文件
/// <summary> /// 裁剪圖片-返回裁剪後的圖片地址 /// </summary> /// <param name="context"></param> /// <returns></returns> private string CutImg(HttpContext context) { string src = context.Request.Params["src"];//原圖片地址 Image file = Image.FromFile(context.Server.MapPath(src));//上傳的圖片 int x = string.IsNullOrEmpty(context.Request.Params["x"]) ? 0 : int.Parse(context.Request.Params["x"]);//左頂點的x坐標 int y = string.IsNullOrEmpty(context.Request.Params["y"]) ? 0 : int.Parse(context.Request.Params["y"]);//右頂點的x坐標 int w = string.IsNullOrEmpty(context.Request.Params["w"]) ? 0 : int.Parse(context.Request.Params["w"]);//截圖的寬度 int h = string.IsNullOrEmpty(context.Request.Params["h"]) ? 0 : int.Parse(context.Request.Params["h"]);//截圖的高度 int maxWidth = string.IsNullOrEmpty(context.Request.Params["maxWidth"]) ? 0 : int.Parse(context.Request.Params["maxWidth"]);//最大寬 int maxHeight = string.IsNullOrEmpty(context.Request.Params["maxHeight"]) ? 0 : int.Parse(context.Request.Params["maxHeight"]);//最大高 string fileExt = Path.GetExtension(src);//圖片格式 string fileName = Guid.NewGuid().ToString("N") + fileExt; string savePath = "/uploadfiles/test/" + DateTime.Now.ToString("yyyyMM") + "/" + fileName; CutImage(GetReducedImage(file, maxHeight, maxHeight), x, y, w, h, savePath, context); return "{\"code\":0,\"src\":\"" + savePath + "\"}"; } /// <summary> /// 生成縮略圖重載方法1,返回縮略圖的Image對象 /// </summary> /// <param name="Width">縮略圖的寬度</param> /// <param name="Height">縮略圖的高度</param> /// <returns>縮略圖的Image對象</returns> public Bitmap GetReducedImage(Image ResourceImage, int Width, int Height) { try { //用指定的大小和格式初始化Bitmap類的新實例 Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); //從指定的Image對象創建新Graphics對象 Graphics graphics = Graphics.FromImage(bitmap); //清除整個繪圖面並以透明背景色填充 graphics.Clear(Color.Transparent); //在指定位置並且按指定大小繪製原圖片對象 graphics.DrawImage(ResourceImage, new Rectangle(0, 0, Width, Height)); return bitmap; } catch (Exception e) { return null; } } /// <summary> /// 截取圖片方法 /// </summary> /// <param name="bitmap">原圖</param> /// <param name="beginX">開始位置-X</param> /// <param name="beginY">開始位置-Y</param> /// <param name="width">截取寬度</param> /// <param name="height">截取長度</param> /// <param name="path">保存路徑</param> /// <param name="context">上下文</param> public static void CutImage(Bitmap bitmap, int beginX, int beginY, int width, int height, string path, HttpContext context) { if (beginX + width > bitmap.Width) beginX = bitmap.Width - width; if (beginY + height > bitmap.Height) beginY = bitmap.Height - height; Bitmap destBitmap = new Bitmap(width, height);//目標圖 Rectangle destRect = new Rectangle(0, 0, width, height);//矩形容器 Rectangle srcRect = new Rectangle(beginX, beginY, width, height); Graphics g = Graphics.FromImage(destBitmap); g.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel); destBitmap.Save(context.Server.MapPath(path), ImageFormat.Jpeg); }點擊確定-後臺進行截圖