原理:利用canvas來實現,將圖片繪制到canvas上,然后canvas轉圖片時,微信提供的一個方法wx.canvasToTempFilePath(Object object, Object this),此方式可以指定生成圖片的質量,下圖是從官方API截的圖:
其中quality可以指定圖片的質量,quality的值越小,圖片越模糊,通過此方法可以實現圖片的壓縮
注意:
1.quality設置只對jpg格式的圖片有效,使用時要將fileType設置為“jpg”, 此舉可能會導致其它格式的圖片變為jpg格式 2.透明背景的png圖片,繪制到canvas上使用此方式導出的圖片是黑色背景,有需求的話是需要canvas先設置背景色的,請小伙伴們注意爬坑。 復制代碼
有了這個參數,壓縮就簡單很多了,下面是代碼:
wxml
<view>
<button bindtap="chooseImage">選擇圖片</button>
</view>
<!-- 展示壓縮后的圖片 -->
<view style="display: flex;justify-content: center;flex-direction: column">
<image width="50" mode="widthFix" src="{{imagePath}}"></image>
</view>
<button wx:if="{{imagePath.length>0}}" bindtap="save">點擊下載壓縮后的圖片</button>
<!-- 用來渲染的canvas -->
<canvas canvas-id='attendCanvasId' class='myCanvas' style='width:{{cWidth}}px;height:{{cHeight}}px;position: fixed;top: -9999px;left: -9999px;'></canvas>
js
Page({
data: {
imagePath: '',
quality: 0.2
},
onLoad: function (options) {
},
/**
* 選項添加圖片事件
*/
chooseImage: function (e) {
var that = this;
wx.chooseImage({
sizeType: ['compressed'], //可選擇原圖或壓縮后的圖片
sourceType: ['album', 'camera'], //可選擇性開放訪問相冊、相機
success: result => {
wx.getImageInfo({
src: result.tempFilePaths[0],
success: function (res) {
that.setData({
cWidth: res.width,
cHeight: res.height
})
that.getCanvasImg(result.tempFilePaths, res.width, res.height, that.data.quality, function (res) {
that.setData({
imagePath: res.tempFilePath
});
});
}
})
}
})
},
/**
* 質量壓縮
*/
getCanvasImg(tempFilePaths, canvasWidth, canvasHeight, quality, callback) {
var that = this;
const ctx = wx.createCanvasContext('attendCanvasId');
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
ctx.drawImage(tempFilePaths[0], 0, 0, canvasWidth, canvasHeight);
ctx.draw(false, function () {
wx.canvasToTempFilePath({
canvasId: 'attendCanvasId',
fileType: 'jpg',
quality: quality,
success: function success(res) {
callback && callback(res)
}, fail: function (e) {
wx.showToast({
title: '圖片上傳失敗,請重新上傳!',
icon: 'none'
})
}
});
});
},
/**
* 圖片保存到相冊
*/
save(e) {
let that = this;
wx.saveImageToPhotosAlbum({
filePath: that.data.imagePath,
success: function (res) {
console.log('圖片已保存');
},
fail: function (res) {
console.log('保存失敗');
}
})
},
})
注意點:
- 注意設置canvas-id='attendCanvasId'
- canvas要離屏渲染,就是移出屏幕之外,但是元素還是顯示的,position: fixed;top: -9999px;left: -9999px; 不能使用 display: none; 這樣是獲取不到canvas元素的。
最后
h5頁面中也有提供這樣的方法
例如這樣子:
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
ctx.drawImage(imagePath, 0, 0, w, h);
canvas.toDataURL('image/jpeg', quality);
作者:orangleLi
鏈接:https://juejin.im/post/5d5df7cf6fb9a06b09361f9a
來源:掘金






