微信小程序 图片裁剪(兼容性最强)

思路

  1. 点击上传图片,调用api wx.chooseImage() 获取到图片的本地临时文件路径列表
  2. 将获取的图片地址传入组件中,进行比例裁剪
  3. 获取裁剪之后的图片,上传到真实的资源地址

流程:

1.

下载组件(image-cropper) 详细操作步骤以及实现各种效果
链接: https://github.com/1977474741/image-cropper.

2.

 "usingComponents": {
        "image-cropper": "../component/image-cropper/image-cropper"
    }

3.

<view style="width:100%;height:500rpx;">
    <image-cropper id="image-cropper" bindload="cropperload" bindimageload="loadimage" bindtapcut="clickcut" limit_move="{{limit_move}}" disable_rotate="{{disable_rotate}}" width="{{width}}" height="{{height}}" imgSrc="{{src}}" angle="{{angle}}" disable_width="{{disable_width}}" max_width="{{max_width}}" max_height="{{max_height}}" disable_height="{{disable_height}}" disable_ratio="{{disable_ratio}}">
    </image-cropper>
</view>
<view class='bottom'>
    <button class="button" catchtap='upload'>上传</button>
    <button bindtap='submit'>确定</button>
</view>

4.

.bottom {
    position: absolute;
    width: 100%;
    bottom: 50rpx;
    display: flex;
    z-index: 10;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    height: 210rpx;
}

button {
    font-size: 27rpx;
    z-index: 2;
    padding: 0 20rpx;
    height: 60rpx;
    min-width: 70rpx;
    margin: 0 4rpx;
}

5.

//获取应用实例
const app = getApp()
Page({
    data: {
        src: '',
        limit_move: true, //是否限制移动
    },
    onLoad: function (options) {
        this.cropper = this.selectComponent("#image-cropper");
        this.setData({
            src: options.imgSrc
        });
        if (!options.imgSrc) {
            this.cropper.upload(); //上传图片
        }
    },

    loadimage(e) {
        wx.hideLoading();
        this.cropper.imgReset();
    },
    upload() {
        let that = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                wx.showLoading({
                    title: '加载中',
                })
                const tempFilePaths = res.tempFilePaths[0];
                //重置图片角度、缩放、位置
                that.cropper.imgReset();
                that.setData({
                    src: tempFilePaths
                });
            }
        })
    },


    submit() {
        this.cropper.getImg((obj) => {
            app.globalData.imgSrc = obj.url;
            wx.navigateBack({
                delta: -1
            })
        });
    },

})

6.

注意:之前在项目中也过别的插件,但是存在兼容性问题,上传按钮会被覆盖导致无法上传

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值