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

  • 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>
相关推荐
wechatbot8882 小时前
【极客互动】企业微信Spring Boot 调度 SearchContact开发自动添加外部联系人网关
汇编·微信·自动化·企业微信·rpa
懂软件的胡子个哥19 小时前
微信二次开发如何保护接口安全,Token、权限和重放防护都要考虑
微信·自动化·wechatapi·个人微信号二次开发·微信群管理
志尊宝19 小时前
Vue3 零基础每日笔记(040):Vite 创建 Vue3 + TS 项目——企业标配从这一篇开始
笔记·vue·html·前端开发·软件开发
前端·柱子20 小时前
q-floodfill白边锯齿?一招搞定抗锯齿边缘问题
前端·html·canva可画
deepfu21 小时前
微信 API 消息模块:发送视频消息的流程与优化点
微信·机器人
iPad协议个微协议1 天前
用 WechatApi 搭建微信自动化系统,需要哪些工程能力
微信·自动化·微信开发·wechatapi·个人微信号二次开发·微信ai客服·微信智能体ai
qq_589666051 天前
移动前端开发之viewport的深入理解
html
微信ipad协议开发1 天前
微信机器人 SaaS 还是私有化部署?两种模式对比选型
微信·机器人
zhanghaha13141 天前
HTML系列教程:17_HTML 框架(frameset、frame、iframe)零基础详解
前端·html
懂软件的胡子个哥1 天前
微信二次开发如何设计高可用架构,服务器故障时消息不能跟着丢
微信·自动化·wechatapi·个人微信号二次开发·微信群管理