1.url 轉(zhuǎn)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轉(zhuǎn)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的頭顷帖,并轉(zhuǎn)化為byte
const bytes = window.atob(arr[1]);
// 處理異常,將ascii碼小于0的轉(zhuǎn)換為大于0
const ab = new ArrayBuffer(bytes.length);
// 生成視圖(直接針對內(nèi)存):8位無符號整數(shù)美旧,長度1個字節(jié)
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
});
}