调用handleDownload方法,传入图片的base64编码,将图片进行导出保存:
// base64 转换blob对象
const base64ToBlob = (base64: string) => {
// 将Base64编码的字符串按';base64,''拆分,得到内容类型和二进制数据两部分
const parts = base64.split(';base64,');
const contentType = parts[0].split(':')[1];
// 将二进制数据转换为UTF-8编码的字符串
const raw = window.atob(parts[1]);
const rawLength = raw.length;
// 创建一个Uint8Array对象,将字符串中的每个字符码存储到这个数组中
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
// 使用Blob对象的构造函数创建一个新的Blob对象,将Uint8Array作为参数传递,并设置内容类型。
return new Blob([uInt8Array], { type: contentType });
}
// 保存二维码
const handleDownload = (base64:string) => {
// 将图片从base64转换为blob对象
const blob = base64ToBlob(base64);
// 创建一个URL对象,用于存储blob对象
const url = URL.createObjectURL(blob);
// 创建一个a标签,用于下载文件
const link = document.createElement('a');
// 设置a标签的href属性,为url对象
link.href = url;
// 设置a标签的download属性,为要下载的文件名
link.download = 'downloaded.png'; // 指定下载文件的名称
// 将a标签添加到body中
document.body.appendChild(link);
// 点击a标签,触发下载
link.click();
// 销毁URL对象
URL.revokeObjectURL(url);
// 从body中移除a标签
document.body.removeChild(link);
}
MDN上关于Data URL的介绍
MDN上关于base64的介绍