微信小程序 图片方案

686 阅读1分钟

图片格式

图片压缩主要从以下三方面考虑

  1. 节省空间(客户端内存空间&云空间)
  2. 减少访问流量(按量计费)
  3. 提升访问速度(用户体验)

因为使用了腾讯云,便引入了tpg格式。压缩率很高

webp

webp 兼容情况,满足大部分情况 image.png

TPG

腾讯自研的图片格式,使用环境需要在支持TGP解码

本地测试:143kb的png => 15.7kb的tpg

微信小程序

iOS

webp

image.png

根据上图,iOS14之后便开始支持webp。

Android

页面展示

TPG 格式,TPG环境之一:安卓 & 微信小程序

预览展示

webp

微信小程序提供了两种预览图片的API

wx.previewImage

wx.preivewMedia

经测试预览图片的环境不支持展示tpg图片,故依旧使用webp格式

代码

// 获取手机系统 android / ios
const systemInfoSync = wx.getSystemInfoSync()
// 根据是否有 Android 字符存在判断
const isAndroid = systemInfoSync.system.indexOf('Android') !== -1

function compressImage(src: string, size: number, preview: boolean = false) {
    if (!src) {
        return src
    }
    
    // 剔除原本的参数
    src = src.split('?')[0]
    
    if (isAndroid) {
        if (preview) {
            return `${src}?imageMogr2/thumbnail/${size}x/format/webp`
        }
        return `${src}?imageMogr2/thumbnail/${size}x/format/tpg`
    }
    
    // iOS 环境
    return `${src}?imageMogr2/thumbnail/${size}x/format/webp`

}

参考

webp兼容

TPG压缩