cropbox.js 头像裁剪插件

cropbox.js

一个轻量级和简单的JavaScript,Jquery,YUI插件来裁剪您的头像。

特征

  • 支持dataUrl显示图像(函数getDataURL)
  • 支持Blob上传图片(函数getBlob)

主流的前端jQuery 图像裁剪插件有JcropCropBox,前者是将原图和需要裁剪的参数(裁剪的各点坐标,旋转角度等)传到后台,然后由后台完成实际的裁剪和后续操作。 CropBox实现功能相对较少,但操作更简单,它的原理是: 将裁减后的图片通过base64编码,然后转化为blob格式发送到服务器,服务器完成解码即可,官网介绍可以看github上的说明和Demo 核心js函数只有两个: getDataURL 将裁剪后的图片简单以base64编码后的结果,用于实时预览,当然也可以将它直接传到服务器,然后解码为png格式 getBlob 上传图片为Blob格式 实现的效果:   前端代码:


<link rel="stylesheet" href="module/cropbox/cropbox.css" /> <script type="text/javascript" src="module/cropbox/cropbox.js"></script> <input name="userId" id="userId" type="hidden" value="1" /> <div class="container"> <div class="imageBox"> <div class="thumbBox"></div> <div class="spinner" style="display: none">Loading...</div> </div> <div class="action"> <div class="new-contentarea tc"> <a href="javascript:void(0)" class="upload-img"> <label for="avatar">上传图像</label> </a> <input type="file" class="" name="avatar" id="avatar" accept="image/*" /> </div> <input type="button" id="btnCrop" class="Btnsty_peyton" value="裁切" /> <input type="button" id="btnZoomIn" class="Btnsty_peyton" value="+" /> <input type="button" id="btnZoomOut" class="Btnsty_peyton" value="-" /> <input type="button" id="blobSubmit" class="Btnsty_peyton" value="提交" /> </div> <div class="cropped"></div> </div> <script> layui.use(['form', 'util', 'config', 'admin'], function () { var form = layui.form; var config = layui.config; var layer = layui.layer; var util = layui.util; var admin = layui.admin; var options = { thumbBox: '.thumbBox', spinner: '.spinner', imgSrc: '/assets/images/timg.jpg' } var cropper = $('.imageBox').cropbox(options); $('#avatar').on('change', function () { var reader = new FileReader(); reader.onload = function (e) { options.imgSrc = e.target.result; //根据MIME判断上传的文件是不是图片类型 if ((options.imgSrc).indexOf("image/") == -1) { parent.layer.alert("文件格式错误,请上传图片类型,如:JPG,JEPG,PNG后缀的文件。", { icon: 2, title: "系统提示" }); } else { cropper = $('.imageBox').cropbox(options); } } reader.readAsDataURL(this.files[0]); }) $('#blobSubmit').on('click', function () { var data = new Object(); data.image = cropper.getDataURL();//base64编码图片 data.userId = $("#userId").val();//用户id data.folder = "HeadImage";//文件夹 var sz = []; sz.push({ width: "180", height: "180" }); sz.push({ width: "128", height: "128" }); sz.push({ width: "64", height: "64" }); data.sizes = sz;//缩略图尺寸 var postdata = JSON.stringify(data); admin.req('sys/headimg', postdata, function (data) { console.log(data); alert('上传成功' + data.data); }, "POST", 'application/json'); }) $('#btnCrop').on('click', function () { var img = cropper.getDataURL(); $('.cropped').html(''); $('.cropped').append('<img src="' + img + '" align="absmiddle" style="width:64px;margin-top:4px;border-radius:64px;box-shadow:0px 0px 12px #7E7E7E;" ><p>64px*64px</p>'); $('.cropped').append('<img src="' + img + '" align="absmiddle" style="width:128px;margin-top:4px;border-radius:128px;box-shadow:0px 0px 12px #7E7E7E;"><p>128px*128px</p>'); $('.cropped').append('<img src="' + img + '" align="absmiddle" style="width:180px;margin-top:4px;border-radius:180px;box-shadow:0px 0px 12px #7E7E7E;"><p>180px*180px</p>'); }) $('#btnZoomIn').on('click', function () { cropper.zoomIn(); }) $('#btnZoomOut').on('click', function () { cropper.zoomOut(); }) }); </script>


  WebApi代码:


/// <summary> /// 上传头像,返回头像路径 /// </summary> /// <param name="info">base64内容</param> /// <returns></returns> public PostResult<string> UploadHeadImage(UploadImageByBase64 info) { info.image.NotNullOrEmpty("没找到需要上传的文件"); if (info.sizes.Count == 0) throw new Exceptions.InvalidDataException("请传入图片规格列表"); var image = info.image; var match = System.Text.RegularExpressions.Regex.Match(image, "data:image/png;base64,([\\w\\W]*)$"); if (match.Success) { image = match.Groups[1].Value; } var domain = string.Empty; var folder = IO.Directory.GetCurrentDirectory() + "//wwwroot//upload/";//先保存到本地,然后云上传 //查询上传配置 var param = db.Queryable<sys_parameter>().First(c => c.key.Equals("upload")).value; var config = JsonHelper.Deserialize<UploadContent>(param); var type = "本地"; if (config.type == 0) { domain = config.local.domain + $"{info.folder}/";//返回域名 folder = config.local.path + $"{info.folder}/";//本地保存路径 } else if (config.type == 1) { type = "七牛云"; domain = config.qiniu.domain; } string filepath = Path.GetDirectoryName(folder); if (!Directory.Exists(filepath)) { if (filepath != null) Directory.CreateDirectory(filepath); } var photoBytes = Convert.FromBase64String(image); var list = new List<sys_uploadfile>(); var outfileNames = new List<string>();//上传成功的文件名集合 foreach (var item in info.sizes) { var filename = $"{info.userId}_{item.width}X{item.height}_{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.png"; ImageSharpHelper.Resize(photoBytes, folder + filename, item.width, item.height); if (config.type == 1) { QiniuCloudHelper.UploadOss(filename, folder, config.qiniu.ak, config.qiniu.sk);//七牛云上传 } list.Add(new sys_uploadfile { type = type, name = filename, folder = folder, extension = ".png", path = filename, url = domain + filename,//域名+文件名 size = "0",////字节 createAt = DateTime.Now, createid = 0 }); outfileNames.Add(domain + filename); } db.Insertable(list).ExecuteCommand(); return new PostResult<string> { data = string.Join(",", outfileNames), msg = "success" }; }


    参考:https://www.cnblogs.com/xzwblog/p/6912320.html cropper(另一种方式截图):https://fly.layui.com/extend/croppers/

posted @ 2019-02-27 19:48  胡椒面  阅读(604)  评论(0编辑  收藏  举报