1、图片url转base64:
const urlToBase64 = async (url) => {
try {
const response = await fetch(url);
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64Data = reader.result.split(",")[1];
resolve(`data:image/png;base64,${base64Data}`);
};
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (error) {
console.error(error);
}
};
2、图片url转二进制(File)文件
const urlToFile = (url, name) => {
return new Promise((resolve, reject) => {
fetch(url)
.then((response) => response.blob())
.then((blob) => {
const file = new File([blob], name, { type: "image/png" });
resolve(file);
})
.catch((error) => {
reject(error);
});
});
};
3、二进制(File)文件转base64
function getBase64(data) {
return new Promise((resolve, reject) => {
const blob = new Blob([data], { type: 'image/png' }) // 必须指定type类型
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject(error)
})
}
4、base64转url
function base64ToUrl(base64Data) {
const byteCharacters = window.atob(base64Data.split(",")[1]);
const byteArrays = [];
for (let i = 0; i < byteCharacters.length; i++) {
byteArrays.push(byteCharacters.charCodeAt(i));
}
const blob = new Blob([new Uint8Array(byteArrays)], {
type: "image/png",
}); // 这里根据实际情况设置图片类型
const imageUrl = URL.createObjectURL(blob);
return imageUrl;
}
以上代码是参考了其他博主的写法
目前我遇到的就这几种,后续有其他的再加上。