关于小程序:微信小程序头像图片压缩上传

4次阅读

共计 1654 个字符,预计需要花费 5 分钟才能阅读完成。

因为 CanvasContext wx.createCanvasContext 进行保护,

导致微信小程序压缩图片性能提醒报错
小程序开发所应用的性能为了避免出现谬误,首先通过 wx.getImageInfo 获取图片信息,之后通过 wx.createOffscreenCanvas 生成画布,最初生成图片,获取到图片的 base64 格局地址,通过 wx.uploadFile 上传后盾。具体代码如下


wxml 文件内容

<button class="head-img" open-type="chooseAvatar" bind:chooseavatar="onChooseAvatar">
    <image class="avatar" src="{{avatarUrl}}"></image>
</button> 

<canvas canvas-id="canvas" id="mycanvas" type="2d" style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"></canvas>

js 文件内容

/**
 * 抉择头像
 */

onChooseAvatar(e) {
    const that = this
    let avatarUrl = e.detail.avatarUrl
    that.compressImage(avatarUrl, 100)
},

/**
 * 压缩图片
 * imageUrl:图片地址
 * width:压缩后的图片宽度
 */
compressImage(imageUrl, width) {
    const that = this;
    wx.getImageInfo({
        src: imageUrl,
        success: res => {
            const height = res.height * width / res.width;
            const offscreenCanvas = wx.createOffscreenCanvas({
                type: '2d',
                width,
                height
            })
            const context = offscreenCanvas.getContext('2d')
            const image = offscreenCanvas.createImage()
            image.src = imageUrl;
            image.onload = () => {context.clearRect(0, 0, width, height)
                context.drawImage(image, 0, 0, width, height)
                const imageBase64 = offscreenCanvas.toDataURL("image/jpeg", 0.7)
                const base64 = imageBase64.replace(/^data:image\/\w+;base64,/, "")
                that.uploadPic(imageUrl, base64)
            }

        }
    })
},

/**
 * 上传图片 
 */
uploadPic(imgData, base64) {
    const that = this;
    // 调用接口上传图片
    let openId = wx.getStorageSync('userOpenid')
    wx.uploadFile({
        url: "https://xxx.xxx.com/upload", // 这里换成你们后端的上传接口即可
        method: 'POST',
        filePath: imgData,
        name: 'file',
        formData: {'content': base64   // 这里传 base64 类型},
        // 胜利回调
        success: (res) => {console.log(res)
            let result = JSON.parse(res.data); // JSON.parse()办法是将 JSON 格局字符串转换为 JSON 对象
            let newAvatarUrl = result.data; // 返回的图片 url
            // 将返回的 url 替换调默认的 url,渲染在页面上
            that.setData({avatarUrl: newAvatarUrl})
        }
    })
},
正文完
 0