js将图片文件或url转成base64字符串
js将图片文件或url链接转成base64字符串
·
js将图片文件或url链接转成base64字符串
代码index.js
/**
* 图片url链接转base64
* @param {String} url 图片链接
* @returns 转base64后的值或者报错信息
*/
const imgUrlToBase64 = (url) => {
return new Promise((resolve, reject) => {
if (!url) {
reject('请传入url内容');
}
if (/\.(png|jpe?g|gif|svg)(\?.*)?$/.test(url)) {
// 图片地址
const image = new Image();
// 设置跨域问题
image.setAttribute('crossOrigin', 'anonymous');
// 图片地址
image.src = url;
image.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage(image, 0, 0, image.width, image.height);
// 获取图片后缀
const ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
// 转base64
const dataUrl = canvas.toDataURL(`image/${ext}`);
resolve(dataUrl || '');
}
} else {
// 非图片地址
reject('非(png/jpe?g/gif/svg等)图片地址');
}
});
};
/**
* 读取图片(或文件)转成base64
* @param {Object} file 图片文件的file,一般是文件上传的file信息
* @returns 转base64后的base64图片地址,或错误信息
*/
const readImgToBase64 = (file) => {
return new Promise((resolve, reject) => {
try {
// 读取信息
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
// 转base64结果
const base64Url = reader.result;
resolve(base64Url);
}
reader.onerror = (err) => {
reject(err);
}
} catch (error) {
reject(error);
}
});
}
使用例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片转Base64</title>
</head>
<body>
<h2>图片链接转base64</h2>
<button id="imageUrlBtn">图片链接转base64</button>
<div id="imageUrlBase64Content" style="width: 90%;word-break: break-all;"></div>
<hr>
<hr>
<input type="file" placeholder="图片文件" id="fileImage">
<p id="fileImageBase64Content" style="width: 90%;word-break: break-all;"></p>
</body>
<script src="./index.js"></script>
<script>
// 图片链接转base64 例子
document.getElementById('imageUrlBtn').onclick = async () => {
const imgUrl = '/@2x.png';
const base64Str = await imgUrlToBase64(imgUrl);
document.getElementById('imageUrlBase64Content').innerHTML = base64Str;
}
// 读取图片(或文件)转成base64 例子
document.getElementById('fileImage').onchange = async (e) => {
const file = e.target.files[0];
const base64Str = await readImgToBase64(file);
console.log('图片base64', base64Str);
document.getElementById('fileImageBase64Content').innerHTML = base64Str;
}
</script>
</html>
更多推荐
已为社区贡献6条内容
所有评论(0)