在小程序中上传文件置媒体库中,可能考虑调用的流畅性,需要对视频镜像 压缩处理。
下面是我代码
index.html 页面只是一个简单的按钮选择
<canvas canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"></canvas>
<button bindtap='choose'>选择图片进行压缩</button>
<image mode='aspectFit' src='{{src}}'></image>
index.js
import regeneratorRuntime from '../../libs/runtime';
Page({
/**
* 页面的初始数据
*/
data: {
cWidth: "",
cHeight: "",
src: ""
},
choose() {
let that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['compressed'], // 指定只能为压缩图,首先进行一次默认压缩
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
async success(photo) {
let a = await that.compressImg(photo.tempFilePaths[0])
console.log(a)
that.setData({
src: a
})
},
})
},
// 压缩功能 参数说明:图片的路径、
async compressImg(photoSrc, ratio = 2, limitNum=100) {
let that=this;
return new Promise((resolve, reject) => {
wx.getImageInfo({
src: photoSrc,
success(res) {
var canvasWidth = res.width //图片原始长宽
var canvasHeight = res.height
console.log('图片的基本信息', res)
while (canvasWidth > limitNum || canvasHeight > limitNum) {// 保证宽高在400以内
canvasWidth = Math.trunc(res.width / ratio)
canvasHeight = Math.trunc(res.height / ratio)
ratio++;
}
that.setData({
cWidth: canvasWidth,
cHeight: canvasHeight
})
//----------绘制图形并取出图片路径--------------
var ctx = wx.createCanvasContext('canvas')
ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
ctx.draw(false, setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'canvas',
destWidth: canvasWidth,
destHeight: canvasHeight,
success: function (res) {
// console.log(res.tempFilePath)//最终图片路径
resolve(res.tempFilePath)
},
fail: function (res) {
console.log(res.errMsg)
}
})
}, 100))
},
fail: function (res) {
console.log(res.errMsg)
},
})
})
}
})