ts 图片类型转换base64,url,file

1.url 转base64
const Img = new Image();
let dataURL = '';
const base: number = Math.random();
Img.src = ${imageUrl}?v=${base}; //imageUrl图片url地址 ``模板字符串
Img.setAttribute('crossOrigin', 'Anonymous');
Img.onload = async function () {
const canvas = document.createElement('canvas');
const {width} = Img;
const {height} = Img;
canvas.width = width;
canvas.height = height;
canvas.getContext('2d')!.drawImage(Img, 0, 0, width, height);
dataURL = canvas.toDataURL('image/jpeg'); //dataURL 图片base64 类型
2.base64转file
const imgFile: any = base64ToBlob(img); //img 图片base64类型

function base64ToBlob(urlData: any) {
const arr = urlData.split(',');
const mime = arr[0].match(/:(.*?);/)[1] || "image/png";
// 去掉url的头,并转化为byte
const bytes = window.atob(arr[1]);
// 处理异常,将ascii码小于0的转换为大于0
const ab = new ArrayBuffer(bytes.length);
// 生成视图(直接针对内存):8位无符号整数,长度1个字节
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new File([ab], "hhh.png", {
type: mime
});
}

你可能感兴趣的:(ts 图片类型转换base64,url,file)