第一步,选择图片
upload_max:定义的图片大小限制;
imagelist:选择的图片数组;
chooseImage() {
uni.chooseImage({
count: 5 ,
sizeType: ['compressed'],
sourceType: ['album', 'camera'], //从相册选择
success: res => {
let number = res.tempFiles.length + this.imagelist.length;
let newtemp = []
for (let i = 0; i < res.tempFiles.length; i++) {
if (Math.ceil(res.tempFiles[i].size / 1024) > this.upload_max *
1024) {
this.compressImage(res.tempFiles[i], number)
} else {
if (number <= 5) {
//不超过限制的图片
} else {
uni.showModal({
title: '提示',
content: '图片总数不能超过5张',
showCancel: false
});
}
}
}
}
});
},2,压缩图片
// 压缩图片
compressImage(urlData, number) {
uni.showLoading({
title: '压缩中...'
})
let _this = this
uni.getImageInfo({
src: urlData.path,
success(res) {
let originWidth = res.width; //图片原始宽
let originHeight = res.height; //图片原始高
let maxWidth = 800;
let maxHeight = 800;
let img = new Image()
img.src = res.path
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d')
// 目标尺寸
let targetWidth = originWidth;
let targetHeight = originHeight;
// if (originWidth > maxWidth || originHeight > maxHeight) {
// if (originWidth / originHeight > maxWidth / maxHeight) {
// // 更宽,按照宽度限定尺寸
// targetWidth = maxWidth;
// targetHeight = Math.round(maxWidth * (originHeight / originWidth));
// } else {
// targetHeight = maxHeight;
// targetWidth = Math.round(maxHeight * (originWidth / originHeight));
// }
// }
canvas.width = targetWidth
canvas.height = targetHeight
// 图片压缩
ctx.drawImage(img, 0, 0, targetWidth, targetHeight)
// canvas对图片进行缩放 0.3是我定义的图片质量,
let base64 = canvas.toDataURL(urlData.type, 0.3);
将base64转换为filel流,
let flie= _this.convertBase64UrlToFile({
dataURL: base64,
type: urlData.type,
contentName: urlData.name
})
console.log('压缩后', flie)
let imgSrc = window.URL.createObjectURL(blod)
_this.imagelist = [..._this.imagelist, {
id: "1a",//标记图片的唯一性,可按自己方式定义
text: imgSrc,
file: flie
}];
uni.hideLoading()
_this.$emit("upImage", _this.imagelist)
},
fail() {
uni.showModal({
title: '提示',
content: '图片压缩失败',
showCancel: false
});
}
})
},
convertBase64UrlToFile(base64) {
let urlData = base64.dataURL
let type = base64.type
let contentName = base64.contentName
let bytes = null
if (urlData.split(',').length > 1) { //是否带前缀
bytes = window.atob(urlData.split(',')[1]) // 去掉url的头,并转换为byte
} else {
bytes = window.atob(urlData)
}
// 处理异常,将ascii码小于0的转换为大于0
let ab = new ArrayBuffer(bytes.length)
let ia = new Uint8Array(ab)
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i)
}
let result = new Blob([ab], {
type: type,
})
let result1 = new File([result], contentName, {
type: type
})
result1.path = window.URL.createObjectURL(result)
return result1
},附言:本人入行不久,只是为了给自己留下笔记,有问题请指出,
版权声明:本文为qq_45580353原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。