<!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>Document</title>
</head>
<body>
<div id = 'app'>
</div>
<script>
let url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242312005c1-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659174217&t=2fd6120db3cd74070561b7e1e112d0e7";
function getBase64(imgUrl) {
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open("get", imgUrl, true);
// 至关重要
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status == 200) {
//得到一个blob对象
var blob = this.response;
// 至关重要
let oFileReader = new FileReader();
oFileReader.onloadend = function (e) {
let base64 = e.target.result;
console.log(base64)
};
oFileReader.readAsDataURL(blob);
//====为了在页面显示图片,可以删除====
}
}
xhr.send();
}
getBase64(url);
</script>
</body>
</html>
运行结果如下
这样我们就成功转换路径为base64格式了 base64的路径直接放给图片路径就可以直接用了
颜色代码如下
<!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>Document</title>
</head>
<body>
<div id = 'app'>
</div>
<script>
let url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242312005c1-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1659174217&t=2fd6120db3cd74070561b7e1e112d0e7";
function getBase64(imgUrl) {
window.URL = window.URL || window.webkitURL;
var xhr = new XMLHttpRequest();
xhr.open("get", imgUrl, true);
// 至关重要
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status == 200) {
//得到一个blob对象
var blob = this.response;
// 至关重要
let oFileReader = new FileReader();
oFileReader.onloadend = function (e) {
let base64 = e.target.result;
console.log(base64)
document.getElementById('app').innerHTML = `<img src = ${
base64} />`;
};
oFileReader.readAsDataURL(blob);
//====为了在页面显示图片,可以删除====
}
}
xhr.send();
}
getBase64(url);
</script>
</body>
</html>
也是非常的简单 主要base64便于后端处理 运行速度上也有优势