在上传图片时,如果太大体积得图片,往往会上传很慢,而且还加大服务器的压力,所以在性能考虑方面来说,可以处理上传图片时先压缩再传给后端
目前原生小程序开发有两种方式进行压缩(原生方法,不排除有第三方接入,但是我目前没找到第三方插件,有找到的大佬们分享一下)这篇先写官方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)
}
})
})
},
预览效果为:压缩效果很明显