一、效果图:
二、实现代码:
/**
* base64转file
* @param {string} urlData base64格式图片
* @returns
*/
export function base64ConvertFile(urlData) {
if (typeof urlData != 'string') {
this.$toast("urlData不是字符串")
return;
}
var arr = urlData.split(',')
var type = arr[0].match(/:(.*?);/)[1]
var fileExt = type.split('/')[1]
var bstr = atob(arr[1])
var n = bstr.length
var u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], `${(Math.random() + '').replace('.', '')}.` + fileExt, {
type: type
});
}
/**
* 压缩图片
* @param {file} file file图片流
* @param {string} minCompress 最小免压体积
* @param {string} imgCompress 压缩比例
* @returns
*/
export function compressImg(file, minCompress, imgCompress) {
// fileSize minCompress 都是M单位
var files;
//转换file流大小为M
var fileSize = file['size'];
// var fileSize = parseFloat(parseInt(file['size']) / 1024 / 1024).toFixed(2);
var read = new FileReader();
read.readAsDataURL(file);
return new Promise(function (resolve) {
read.onload = function (e) {
var img = new Image();
img.src = e.target.result;
img.onload = function () {
//默认按比例压缩
var w = this.width,
h = this.height;
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var base64;
// 创建属性节点
canvas.setAttribute("width", w);
canvas.setAttribute("height", h);
//把画布背景颜色设置成白色,画布背景颜色默认黑色
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, w, h);
ctx.drawImage(this, 0, 0, w, h);
//如果图片小于minCompress 那么不执行压缩操作
if (fileSize < minCompress) {
base64 = canvas.toDataURL('image/jpeg', 0.9);
} else {
base64 = canvas.toDataURL('image/jpeg', imgCompress);
}
// 回调函数返回file的值(将base64编码转成file)
files = base64ConvertFile(base64); //如果后台接收类型为base64的话这一步可以省略
resolve({
content: base64,
file: files
})
};
};
})
}