前端图片处理(base64、blob、url、canvas 转换)
1. 图片 url 转 blob
将前端项目中的预置图片引用 url 转为 blob,使用 fetch 方法(不可跨域)。
import vueImage from '../assets/vue.svg';
const urlToBlob = async (url: string): Promise<Blob> => {
const response = await fetch(url); // 获取文件内容
const blob = await response.blob(); // 转成 blob
return blob;
}
2. blob 转 base64
创建 FileReader 对象,以 dataURL 方式读取文件。
const blobToDataURL = (blob: Blob): Promise<string> => {
return new Promise((resolve) => {
const reader = new FileReader();
// 读取完成后获取结果
reader.addEventListener('load', () => {
resolve(reader.result as string);
})
if (blob) reader.readAsDataURL(blob); // 以 dataURL 方式读取文件
})
}
3. base64 转 blob
将 dataURL 分割,得到文件类型和 base64 字符串,解码 base64 得到二进制数据字符串,将文件类型和二进制数据字符串传入 Blob 构造函数,获取 blob。
const dataURLToBlob = (dataURL: string): Blob => {
const arr = dataURL.split(',');
const mimeType = arr[0].match(/:(.*?);/)?.[1]; // 文件类型
const binaryStr = atob(arr[1]); // 解码 base64
const blob = new Blob([...binaryStr], { type: mimeType });
return blob;
}
4. blob 转 url
通过 URL.createObjectURL() 方法获取 blob 对象的引用 URL,这个 URL 的生命周期和创建它的窗口中的 document 绑定。
const blobToUrl = (blob: Blob): string => {
const url = URL.createObjectURL(blob);
console.log(url); // blob:http://localhost:5173/7b5a13a3-d5b4-4091-9492-c6f42882887f
return url;
}
5. HTMLElement 转 blob(canvas 转 blob)
通过 html2canvas 将 html 元素转为 canvas,再通过 canvas.toBlob() 方法获取 blob。
const HTMLElementToBlob = (): Promise<Blob | null> => {
return new Promise(resolve => {
const element: HTMLElement | null = document.getElementById('elementId'); // 获取 html 元素
if (element) {
// 将 html 元素转为 canvas
html2canvas(element, {
scale: 4,
logging: false,
}).then((canvas: HTMLCanvasElement) => {
const mimeType = 'image/png'; // 要转化的文件类型
canvas.toBlob(blob => {
resolve(blob);
}, mimeType);
});
}
});
};
还可通过 canvas.toDataURL() 方法获取 base64 字符串。