短视频带货源码,图片上传前的缩放和压缩操作
作者:互联网
短视频带货源码,图片上传前的缩放和压缩操作
<canvas canvas-id='attendCanvasId' class='myCanvas' style="width:{{canvasWidth}}px; height:{{canvasHeight}}px;"></canvas>
.myCanvas{
background:#000;
margin:30rpx auto;
position:absolute;
right:1440px;
top: -1440px;
}
//页面所需定义的data
data = {
canvasWidth: 0, // canvas长度
canvasHeight: 0, //canvas高度
originalFileInfoArr:[],//图片缩放压缩后保存的临时数组
}
//选择照片
select_img(){
var that= this
wx.chooseImage({
count: 1,
success(res) {
if(res.tempFiles.length>0){
that.getCanvasImg(res.tempFiles) // 通过canvas进行缩放
}
wx.showLoading({ title: 'Loading...'});
}
})
}
//缩放操作(将图片的最长边缩至1440,短边等比例缩放)
getCanvasImg(tempFiles){
var that = this
// 获取图片信息来设置canvas的长高
wx.getImageInfo({
src: tempFiles[0].path,
success(imgDetail){
var maxWidth = 1440 // 最大长度
var maxHeight = 1440 // 最大高度
var bili = imgDetail.width/imgDetail.height // 获取图片长高比例
if(imgDetail.width>maxWidth || imgDetail.height>maxHeight){
if(imgDetail.width >= imgDetail.height){ // 长图或正方形
that.canvasWidth = maxWidth
that.canvasHeight = Number(maxWidth/bili).toFixed(0)
}else{ // 高图
that.canvasHeight = maxHeight
that.canvasWidth = Number(maxHeight*bili).toFixed(0)
}
const ctx = wx.createCanvasContext('attendCanvasId');
ctx.drawImage(imgDetail.path, 0, 0, Number(that.canvasWidth), Number(that.canvasHeight));
ctx.draw(false, function () {
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'attendCanvasId',
success(res) {
that.compressImg(res.tempFilePath) // 缩放成功后压缩
},
fail(res) {
wx.showToast({ title: 'canvas缩放失败', icon: 'none'});
}
});
}, 200);
});
}else{ // 图片最长边未超过1440,无需进行缩放,直接掉起压缩方法
that.canvasWidth = imgDetail.width
that.canvasHeight = imgDetail.height
that.compressImg(imgDetail.path)
}
}
})
}
//压缩操作
compressImg(path){
var that = this
wx.compressImage({
src: path,
quality: 75, // 压缩质量
success(e){
let i = e.tempFilePath.lastIndexOf ('.',(e.tempFilePath.lastIndexOf (".")-1));
let name = e.tempFilePath.substring(i+1, e.tempFilePath.length) //截取到微信临时路径的最后一段名称
//保存到临时数组,可以遍历通过image标签在前端显示
that.originalFileInfoArr.push({name:name, size:500, filePath:e.tempFilePath})
wx.hideLoading();
},
fail(){
wx.showToast({ title: '压缩失败', icon: 'none'});
}
})
}
以上就是 短视频带货源码,图片上传前的缩放和压缩操作,更多内容欢迎关注之后的文章
标签:货源,res,缩放,tempFilePath,imgDetail,var,上传,wx 来源: https://www.cnblogs.com/yunbaomengnan/p/16301053.html