本地图片地址转换base64方法typeScript方法
const getBase64 = (url: string) => { return new Promise((resolve, reject) => { // 通过构造函数来创建的 img 实例,在赋予 src 值后就会立刻下载图片,避免了文档冗余和污染 let Img = new Image(); Img.src = url; Img.crossOrigin = 'Anonymous'; Img.onload = () => { // 要先确保图片完整获取到,这是个异步事件 let dataURL = ''; let canvas = document.createElement('canvas'); // 创建canvas元素 let width = Img.width; // 确保canvas的尺寸和图片一样 let height = Img.height; canvas.width = width || 0; canvas.height = height || 0; let ctx = canvas.getContext('2d'); if (ctx) ctx.drawImage(Img, 0, 0, width, height); // 将图片绘制到canvas中 dataURL = canvas.toDataURL('image/jpeg'); // 转换图片为dataURL resolve(dataURL); }; }); }
调用:
let res = await getBase64('图片地址'); 或者 getBase64('图片地址').then((thumbnail: any) => { //TODO });