美文网首页
小程序裁剪、旋转图片

小程序裁剪、旋转图片

作者: 全栈的猫南北 | 来源:发表于2022-03-07 17:48 被阅读0次

小程序本身api的wx.previewImage方法不支持旋转,而项目需求是上传证件照支持旋转、裁剪、缩放如下图。

图片.png

1、当证件数组(certificateList)没有上传照片时使用自封装JumpImage组件

        <JumpImage wx:if="{{!item.accessoryUrl}}" listNamStr="certificateList" listitemStr="accessoryUrl" listitemid="accessoryId" listIndex ="{{index}}" >
                    </JumpImage>

2、封装JumpImage组件(第一层组件)接收参数并传递到下层页面

JumpImage.xml

<view class="i-wrap-add"  bindtap="upImg" >
  <view> <i class="iconfont icontianjia1 c9"></i>
    <p>上传照片</p>
  </view>
</view>

JumpImage.js

/**
     * 组件的对外属性
     */
    properties: {

        listNamStr: {
            type: String,
            value: "",
        }, //数组名字
        listitemStr: {
            type: String,
            value: ""
        }, //item名字
        listitemid: {
            type: String,
            value: ""
        }, //itemid
        listIndex: {
            type: [String, Number],
            value: 0
        }, //数字标识
},
    /**
     * 组件的方法列表
     */
    methods: {

        upImg(e) {
            let index = this.properties.listIndex
            let certificateList = this.properties.listNamStr
            let accessoryUrl = `${certificateList}[${index}].${this.properties.listitemStr}`
            let accessoryId = `${certificateList}[${index}].${this.properties.listitemid}`
            wx.chooseImage({
                count: 1,
                success: function (ress) {
                    wx.navigateTo({
                        url: `/pages/editImage/editImage?filepath=${ress.tempFilePaths[0]}&index=${index}&listitemStr=${accessoryUrl}&listitemid=${accessoryId}`,
                    })
 
                },
            })
        },
    }

3、editImage编辑图片页面

editImage.js

onload接收上个页面的属性

    if (options.filepath) {
      this.setData({
        originUrl: options.filepath,
      })
    }
    if (options.index) {
      this.setData({
        index: options.index
      })
    }
    if (options.listitemStr) {
      this.setData({
        listitemStr: options.listitemStr
      })
    }
    if (options.listitemid) {
      this.setData({
        listitemid: options.listitemid
      })
    }

调用第二层组件cropper的确定按钮的回调方法,把图片URL、id信息赋值给上个页面

//确定图片
  getCropperImg(e) {
    let pages = getCurrentPages();
    let beforePage = pages[pages.length - 2];

    let index = parseFloat(this.data.index)
    let certificateList = beforePage.data.certificateList    
    let accessoryUrl = this.data.listitemStr
    let accessoryId = this.data.listitemid
    let this_ = beforePage 
    let fileId = ''
    
    util.upLoadFiles({
      accessoryUrl: e.detail.url,
      successCallBack: function (res) {

        let data = JSON.parse(res.data)
        fileId = data.data
        this_.setData({
          [accessoryUrl]: e.detail.url,
          [accessoryId]: fileId
        })
      }
    })
    wx.navigateBack({
      delta: 0,
    })
  },
editImage.xml给cropper第二层组件设置尺寸和图片url
  <view class='cropper' wx:if="{{originUrl}}">
    <cropper bind:getCropperImg="getCropperImg" url="{{ originUrl }}" ratio="{{ ratio }}"></cropper> 
  </view>

4、第二层组件cropper

cropper.xml

<view class="container">
  <!--  剪裁框与初始图片,剪裁框监听用户手势,获取移动缩放旋转值,images通过css样式显示变化  -->
  <view class="img" style="width:{{ width }}px; height:{{height}}px" catchtouchstart="touchstartCallback"  catchtouchmove="touchmoveCallback" catchtouchend="touchendCallback"  >
    <image style="transform: translate({{stv.offsetX}}px, {{stv.offsetY}}px) scale({{stv.scale}}) rotate({{ stv.rotate }}deg);width:{{originImg.width}}px; height: {{originImg.height}}px" src="{{ originImg.url }}"></image>
  </view>
  <view class='footer'>
      <view bindtap='rotate'>旋转</view>
      <view bindtap='cropperImg'>确定</view>
  </view>
  <!--  canvas长宽设为初始图片设置的长款的两倍,使剪裁得到的图片更清晰,也不至于过大  -->
  <canvas class='imgcrop' style="width:{{ width * 2 }}px;height:{{ height * 2}}px;" canvas-id='imgcrop'></canvas>
</view>

cropper.js

// 确定保存canvas剪裁图片,并triggerEvent回调生成的本地图片路径
    cropperImg() {
      wx.showLoading({
        title: 'loading',
        mask: true
      })
      let _this = this;
      let ctx = wx.createCanvasContext('imgcrop',this);
      let cropData = _this.data.stv;
      ctx.save();
      // 缩放偏移值
      let x = (_this.data.originImg.width - _this.data.originImg.width * cropData.scale) / 2;
      let y = (_this.data.originImg.height - _this.data.originImg.height * cropData.scale) / 2;

      //画布中点坐标转移到图片中心
      let movex = (cropData.offsetX + x) * 2 + _this.data.originImg.width * cropData.scale;
      let movey = (cropData.offsetY + y) * 2 + _this.data.originImg.height * cropData.scale;
      ctx.translate(movex, movey);
      ctx.rotate(cropData.rotate * Math.PI / 180);
      ctx.translate(-movex, -movey);
      
      ctx.drawImage(_this.data.originImg.url, (cropData.offsetX + x) * 2, (cropData.offsetY + y) * 2, _this.data.originImg.width * 2 * cropData.scale, _this.data.originImg.height * 2 * cropData.scale);
      ctx.restore();
      ctx.draw(false, ()=> {
        wx.canvasToTempFilePath({
          canvasId: 'imgcrop',
          success(response) {
            console.log(response.tempFilePath);
            _this.triggerEvent("getCropperImg", { url: response.tempFilePath })
            wx.hideLoading();
          },
          fail( e ) {
            console.log( e );
            wx.hideLoading();
            wx.showToast({
              title: '生成图片失败',
              icon: 'none'
            })
          }
        }, this)
      });
    },

用到组件:https://github.com/yuanwyj/Mini-Program-cropper

相关文章

网友评论

      本文标题:小程序裁剪、旋转图片

      本文链接:https://www.haomeiwen.com/subject/lsayrrtx.html