微信小程序上传图片使用compressImage压缩

本文介绍了在微信小程序中如何处理大体积图片上传的问题,通过使用wx.compressImage官方API进行图片压缩,以提高上传速度和减轻服务器压力。同时提到iOS平台的特殊处理和压缩效果预览。
摘要由CSDN通过智能技术生成

在上传图片时,如果太大体积得图片,往往会上传很慢,而且还加大服务器的压力,所以在性能考虑方面来说,可以处理上传图片时先压缩再传给后端

目前原生小程序开发有两种方式进行压缩(原生方法,不排除有第三方接入,但是我目前没找到第三方插件,有找到的大佬们分享一下)这篇先写官方api压缩

compressImage压缩

这个是官方api压缩方法,但是偶现兼容问题,仅对jpg图片有效

1、选择图片使用wx.chooseMedia
<button bindtap="changeImage">选择图片</button>
<view wx:for="{{pic}}" wx:key="key">
  <image src="{{item}}" style="width:100%;height:{{compressH}}px" mode='aspectFill' bindtap="see"></image>
</view>
  changeImage() {
        let that = this
        // 图片限制大小
        const fileLimit = 2 * 1024 * 1024
        // 选择图片原图或是压缩图
        wx.chooseMedia({
            sizeType: ['original', 'compressed'],
            count: 9,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            success: async function (res) {
                let tempFiles = res.tempFiles
                if (tempFiles.length) {
                    for (let i = 0; i < tempFiles.length; i++) {
                        let filePath = tempFiles[i].tempFilePath
                        const size = tempFiles[i].size / 1024 / 1024;
                        that.setData({
                            sizeBefore: size,
                        })
                        // 图片超过大小限制
                        // 手动压缩
                        filePath = await that.compressFile(filePath, i, tempFiles[i].size)
                        // 上传图片
                        that.setData({
                            pic: [filePath] // 将图片路径设置到数据中,用于在页面上显示
                        });
                        // 获取压缩后图片的信息,包括大小等
                        wx.getFileSystemManager().getFileInfo({
                            filePath: filePath,
                            success: fileInfo => {
                                that.setData({
                                    compressSize: fileInfo.size / 1024 / 1024
                                })
                            },
                            fail: err => {
                                console.error('获取压缩后图片信息失败:', err);
                            }
                        });
                    }
                }
            }
        })
    },
2、wx.compressImage压缩

注意:ios因为自己有压缩机制,压缩到极致就不会再压,因此往小了写
压缩质量可以根据大小变化,自己设置就行,我这里就直接写10
还要最重要的是压缩后图片显示的高度,代码如下,如果不是这样子设置,图片会显示不全

 const windowWidth= wx.getSystemInfoSync().windowWidth;
  let imgRatio = imgHeight/imgWidth;
    that.setData({
        compressH: windowWidth * imgRatio
    })

       compressFile(src, i, size) {
        let that = this
        return new Promise((resolve) => {
            // 获取图片信息
            wx.getImageInfo({
                src,
                success: (img) => {
                    let imgWidth = img.width
                    let imgHeight = img.height
                    //这段必看!!!!
                       const windowWidth= wx.getSystemInfoSync().windowWidth;
                        let imgRatio = imgHeight/imgWidth;
                        that.setData({
                            compressH: windowWidth * imgRatio
                        })
                        that.compressImage(src, size).then(res => {
                            resolve(res)
                        })
                },
                fail: () => {
                    that.compressImage(src, size).then(res => {
                        resolve(res)
                    })
                }
            })
        })
    },
     compressImage(src, size) {
        let that = this
        return new Promise((resolve, reject) => {
            let quality = 100
            // ios因为自己有压缩机制,压缩到极致就不会再压,因此往小了写
            if (this.data.isIOS) {
                quality = 0.1
            } else {
                let temp = 30 - parseInt(size / 1024 / 1024)
                quality = temp < 10 ? 10 : temp
            }
            that.setData({
                quality: quality //测试后 ios 0.1  安卓压缩仅对jpg图片压缩
            })
            wx.compressImage({
                src, // 图片路径
                quality: 10, // 压缩质量
                success: function (res) {
                    console.log('官方API压缩res', res, quality)

                    resolve(res.tempFilePath)
                },
                fail: function (err) {
                    resolve(src)
                }
            })
        })
    },

预览效果为:压缩效果很明显
在这里插入图片描述

  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值