【前端开发】微信裁剪图片上传

  • Cropper.js: 一款基于 JavaScript 的开源图片裁剪神器,支持图片裁剪、缩放、旋转

HTML页面引用:

css:<link rel="stylesheet" type="text/css" href="css/cropper.css" />

js:<script type="text/javascript"src="js/cropper.js" charset="utf-8"></script>

html 复制代码
<!DOCTYPE html>
<html lang="en" style="font-size: 50px">
<head>
    <meta charset="UTF-8">
    <title>裁剪相片上传</title>
    <link rel="stylesheet" type="text/css" href="css/cropper.css" />
    <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=8">
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
</head>
<body>
    <div class="wrapper">
        <div class="uploadtop">
            <div class="imgdiv">
                <div class="add">
                    <input
                    type="file"
                    name="fileInput"
                    id="fileInput"
                    accept="image/*"
                    class="hidden-input"
                  />
                    <img src="./img/photoCollection/upload.png" alt="">
                    <span>拍照</span>
                </div>
                <img id="image">
            </div>
        </div>
         <div class="btn-box">
             <div class="next uploadbtn">上传相片</div>
         </div>
    </div>
    <script type="text/javascript" src="/js/jquery.min.js"></script>
    <script type="text/javascript"src="js/cropper.js" charset="utf-8"></script>
    <script>
		// 上传图片对象
		let uploadFile = {};
		var imageArr = "";
		let cropperInstance = null;
		var ImgCutH = "";
		var ImgCutW = "";
		var ImgCutX = 0;
		var ImgCutY = 0;
		
		$("#fileInput").on("change", handleFileChange);
		// 获取文件上传对象
		function handleFileChange(event) {
		  uploadFile = event.target.files[0];
		
		  var fileSuffix = uploadFile.name.substr(uploadFile.name.indexOf("."));
		  //判断图片上传的格式
		  if (!/\.(jpg|JPG)$/.test(fileSuffix)) {
		    weui.alert("请上传格式为jpg的图片!");
		    return;
		  }
		
		  var reader = new FileReader();
		  reader.readAsDataURL(uploadFile);
		  reader.onload = function () {
		    imageArr = reader.result;
		    $("#image")
		      .cropper("destroy") // 销毁旧的裁剪区域
		      .attr("src", imageArr) // 重新设置图片路径
		      .cropper({
		        aspectRatio: 3 / 4,
		        viewMode: 1,
		        dragMode: "move",
		        rotatable: false,
		        movable: true, //是否允许可以移动后面的图片
		        checkCrossOrigin: false,
		        // preview:small,
		        center: true, //裁剪框在图片是否居中
		        crop: function (e) {
		          ImgCutH = parseInt(e.detail.height);
		          ImgCutW = parseInt(e.detail.width);
		          ImgCutX = parseInt(e.detail.x);
		          ImgCutY = parseInt(e.detail.y);
		        },
		      });
		
		    // 保存 cropper 实例
		    cropperInstance = $("#image").data("cropper");
		  };
		}
		
		// 提交文件
		$(".uploadbtn").on("click", function () {
		  if (imageArr == "") {
		    weui.alert("请选择图片!");
		  } else {
		    // 获取裁剪后的图片为 Blob 格式
		    const croppedCanvas = cropperInstance
		      .getCroppedCanvas()
		      .toBlob((croppedBlob) => {
		        // 将裁剪后的图片 Blob 对象转为文件
		        const croppedFile = new File([croppedBlob], uploadFile.name, {
		          type: uploadFile.type,
		          lastModified: new Date().getTime(),
		        });
		
		        uploadFile = croppedFile;
		
		        // 上传裁剪后的图片
		        uploadImageFile();
		      }, "image/jpeg");
		  }
		});
		
		// 上传到服务器
		function uploadImageFile(callback) {
		  var formData = new FormData();
		  formData.append("file", uploadFile);
		
		  $.ajax({
		    url: handlerURL,
		    type: "post",
		    data: formData,
		    processData: false,
		    contentType: false,
		    dataType: "json",
		    success: function (req) {
		      if (req.Status) {
		        imageArr = req.Data;
		        callback();
		      }
		    },
		    error: function (statusText) {
		      console.error(statusText);
		    },
		  });
		}

	</script>
</body>
</html>
相关推荐
Jinkey2 天前
要用户手机号真的是为了打骚扰电话吗?浅谈微信生态会员账号体系与资产合并
后端·微信·微信小程序
anOnion3 天前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
米丘4 天前
微前端之 Web Components 完全指南
微服务·html
保持当下6 天前
分享一些程序员很棘手但是却又简单的工具
程序员·免费·js·工具
2601_961845157 天前
粉笔行测题库|系统班|刷题
网络·百度·微信·微信公众平台·facebook·新浪微博
Metaphor6927 天前
使用 Python 将 PDF 转换为 HTML
python·pdf·html
a1117767 天前
“黑夜流星“个人引导页 网页html
java·前端·html
JieE2127 天前
手把手带你用纯 CSS 实现一个 3D 旋转魔方,这些前端基础你能打几分?
前端·css·html
YHL7 天前
🧊 CSS 3D 硬核解析:四个属性手写旋转立方体
前端·css·html
a1117767 天前
无限森林漫游(简约几何版 html
前端·html