十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
本文主要讲解基于 Vue + Vant ,实现移动端图片选择,并用 Canvas 压缩图片,最后上传至服务器。还会封装一个工具类,方便直接调用。

一、工具类封装
废话不多说先上代码,封装一个 CompressImageUtils 工具类:
**
* 图片压缩工具类
* 大高度和大宽度都为 500,如果超出大小将等比例缩放。
*
* 注意可能出现压缩后比原图更大的情况,在调用的地方自己判断大小并决定上传压缩前或压缩后的图到服务器。
*/
// 将base64转换为blob
export function convertBase64UrlToBlob(urlData) {
let arr = urlData.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], {type: mime})
}
// 压缩图片
export function compressImage(path) {
//大高度
const maxHeight = 500;
//大宽度
const maxWidth = 500;
return new Promise((resolve, reject) => {
let img = new Image();
img.src = path;
img.onload = function () {
const originHeight = img.height;
const originWidth = img.width;
let compressedWidth = img.height;
let compressedHeight = img.width;
if ((originWidth > maxWidth) && (originHeight > maxHeight)) {
// 更宽更高,
if ((originHeight / originWidth) > (maxHeight / maxWidth)) {
// 更加严重的高窄型,确定大高,压缩宽度
compressedHeight = maxHeight
compressedWidth = maxHeight * (originWidth / originHeight)
} else {
//更加严重的矮宽型, 确定大宽,压缩高度
compressedWidth = maxWidth
compressedHeight = maxWidth * (originHeight / originWidth)
}
} else if (originWidth > maxWidth && originHeight <= maxHeight) {
// 更宽,但比较矮,以maxWidth作为基准
compressedWidth = maxWidth
compressedHeight = maxWidth * (originHeight / originWidth)
} else if (originWidth <= maxWidth && originHeight > maxHeight) {
// 比较窄,但很高,取maxHight为基准
compressedHeight = maxHeight
compressedWidth = maxHeight * (originWidth / originHeight)
} else {
// 符合宽高限制,不做压缩
}
// 生成canvas
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.height = compressedHeight;
canvas.width = compressedWidth;
context.clearRect(0, 0, compressedWidth, compressedHeight);
context.drawImage(img, 0, 0, compressedWidth, compressedHeight);
let base64 = canvas.toDataURL('image/*', 0.8);
let blob = convertBase64UrlToBlob(base64);
// 回调函数返回blob的值。也可根据自己的需求返回base64的值
resolve(blob)
}
})
}
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。