将图片转换为Base64
function getImgToBase64(url,callback){
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
var dataURL = canvas.toDataURL('image/png');
callback(dataURL);
canvas = null;
};
img.src = url;
}
将base64转换为file类型
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
可以将图片转换为base64
getImgToBase64('img/test.png',function(data){
var myFile = dataURLtoFile(data,'testimgtestimgtestimg');
console.log(myFile);
});
Base64 转化成图片格式
function dataURLtoFile(dataurl, filename = 'file') {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let suffix = mime.split('/')[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
})
}
var base64Img = imgDataUrl // base64编码的图片
var imgFile = dataURLtoFile(base64Img)
console.log('imgFile====>', imgFile)