export function image2Base64(file, maxW, maxH) {
return new Promise(resolve => {
// 后缀名
const type = file.name.split('.').pop();
// 文件路径
const dataURl = (window.URL || window.webkitURL).createObjectURL(file);
var img = new Image();
img.src = dataURl;
img.onload = function() {
const canvas = document.createElement('canvas');
if (img.width > maxW || img.height > maxH) {
let w = maxW;
let h = maxW * img.height / img.width;
if (h > maxH) {
w = maxH * img.width / img.height;
h = maxH;
}
canvas.width = w;
canvas.height = h;
} else {
canvas.width = img.width;
canvas.height = img.height;
}
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL('image/' + type);
resolve(dataURL);
};
});
}
export function image2Base64_2(file) {
return new Promise(resolve => {
const type = file.name.split('.').pop();
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
const url = this.result.substring(this.result.indexOf(',') + 1);
const imgUrl = `data:image/${type};base64,${url}`
resolve(imgUrl);
}
})
}
function change(ev) {
const file = ev.target.files[0];
if (file.size > 2e6) {
alert('图片大小不能超过2M');
return;
}
image2Base64(file, 300, 200).then(base64 => {
console.log(base64);
})
}
网友评论