uniapp上传图片前压缩

该博客介绍了在uniapp中实现图片上传前的压缩功能,通过选择图片、压缩图片到指定尺寸并上传到服务器的过程。主要涉及uni.chooseImage、FileReader、Canvas等API的使用,确保图片不超过一定大小并提高上传效率。
摘要由CSDN通过智能技术生成

uniapp上传图片前压缩

  • 结构
 <!--图片上传-->
        <view>
          <view
            class="uni-hello-addfile demo"
            @click="chooseImage"
            v-if="imageSrc.length < 9"
            >+ 图片({{ imageSrc.length }}/9)
          </view>
          <scroll-view
            :scroll-top="scrollTop"
            scroll-y="true"
            class="scroll-Y"
            style="max-height: 5.333rem;margin-top: 0.533rem  /* 10/18.75 */;"
            @scroll.stop.prevent="scroll"
            v-if="imageSrc"
          >
            <view v-for="(imgSrc, imgIndex) in imageSrc" class="img">
              <image
                :src="judgeImgSrc(imgSrc)"
                @click="preview(imgIndex)"
                class="img2"
              ></image>
              <uni-icons
                type="close"
                size="20"
                style="position: absolute;right: 0;top: 0;"
                color="#1890FF"
                @click="deleteImg(imgIndex)"
              ></uni-icons>
            </view>
          </scroll-view>
        </view>
  • 方法
//选择图片
    chooseImage: function() {
      let _this = this;
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album"],
        success: (res) => {
          console.log("success", res.tempFiles[0]);
          // if (res.tempFiles[0].size > 10 * 1024 * 1024) {
          //   uni.showToast({
          //     title: "文件大小超过10M",
          //     image: "/static/fail.png",
          //     duration: 2000,
          //   });
          //   return false;
          // }
          uni.showLoading({
            title: "正在上传...",
            duration: 2000,
          });
          console.log("文件信息", res.tempFilePaths[0], res.tempFiles[0].size);
          let path = res.tempFilePaths[0];
          let reader = new FileReader();
          reader.readAsDataURL(res.tempFiles[0]);
          reader.onload = function(e) {
            let base64 = e.target.result; //转码过后的base64编码
            console.log("压缩前", e);
            let content = path; //图片的src,base64格式
            let img = new Image();
            img.src = content;
            img.onload = function() {
              //图片加载完毕
              _this.compressEvent(img, (dataURL) => {
                // console.log("dataURL", dataURL); //base64                
                _this.uploadImg(dataURL); //这是上传图片的方法
              });
            };
          };
        },
        fail: (err) => {
          // #ifdef MP
          uni.getSetting({
            success: (res) => {
              let authStatus = res.authSetting["scope.album"];
              if (!authStatus) {
                uni.showModal({
                  title: "授权失败",
                  content: "需要从您的相册获取图片,请在设置界面打开相关权限",
                  success: (res) => {
                    if (res.confirm) {
                      uni.openSetting();
                    }
                  },
                });
              }
            },
          });
          // #endif
        },
      });
    },
    //上传图片
    uploadImg(img) {
      let that = this;
      uni.uploadFile({
        url: that.$store.state.commonUrl + "/api/sub-user/upload-image",
        filePath: img,
        fileType: "image",
        name: "fileInfo",
        formData: {
          uid: localStorage.getItem("uid"),
        },
        header: {
          Authorization: "Bearer " + localStorage.getItem("token"),
        },
        success: (res) => {
          uni.hideLoading();
          if (JSON.parse(res.data).error == 0) {
            uni.showToast({
              title: "上传成功",
              icon: "success",
              duration: 2000,
            });
            that.imageSrc.push(JSON.parse(res.data).data.local_path);
          } else {
            uni.showToast({
              title: JSON.parse(res.data).error_msg,
              image: "/static/fail.png",
              duration: 2000,
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.errMsg,
            showCancel: false,
          });
        },
      });
    },
    //压缩
    compressEvent(img, callback) {
      let canvasWidth = img.width; //图片原始宽高
      let canvasHeight = img.height;
      //图片宽高比
      let base = canvasWidth / canvasHeight;
      //宽度最大设为1024
      if (canvasWidth > 1024) {
        canvasWidth = 1024;
        canvasHeight = Math.floor(canvasWidth / base);
      }
      //绘制图像到画布
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      canvas.width = canvasWidth;
      canvas.height = canvasHeight;
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      //将画布转为base64,mimeType类型为image/jpeg,图片质量为0.3
      let dataURL = canvas.toDataURL("image/jpeg", 0.3);
      // console.log("压缩中", dataURL);
      callback ? callback(dataURL) : null; //调用回调函数
    },```

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
uniapp是一款基于Vue.js和小程序开发框架的跨平台应用开发工具,它可以帮助开发者快速构建同时在多个平台上运行的应用程序。在uniapp开发中,如果需要上传图片,可以选择使用图片压缩插件来减小图片的大小,提高上传效率。 目uniapp上使用的图片压缩插件主要有两种方式:基于canvas的压缩和使用第三方压缩库。 基于canvas的压缩方法是先将图片绘制到一个canvas上,然后通过调整canvas的尺寸和图片的质量来进行压缩。这种方法可以确保压缩图片的质量,但在处理大尺寸图片时可能会占用较多的内存,导致用户体验下降。 另一种方法是使用第三方压缩库,如compressorjs和image-compressor等。这些库使用了一些压缩算法来减小图片的大小,同时保持适当的质量。使用第三方压缩库通常需要在项目中引入相应的插件,并按照插件提供的API进行调用。 具体使用图片压缩插件的步骤如下: 1. 引入图片压缩插件的相关依赖库或插件。 2. 创建一个图片上传组件,并添加上传按钮。 3. 在图片上传事件中获取用户选择的图片文件。 4. 调用图片压缩插件的API对图片进行压缩处理。 5. 将压缩后的图片上传到服务器。 值得注意的是,图片压缩并不是每个项目都必须使用的功能,需要根据具体需求和项目的实际情况来决定是否使用以及选择哪种压缩方法。另外,使用图片压缩插件时,需要考虑用户上传的图片大小和质量要求,以及对用户设备性能的影响。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值