1、本地图片 File 对象转换为 Data URL
<input type="file" accept="image/*" onchange="loadFile(event)" /> <img id="image" /> <script> function loadFile(event) { const reader = new FileReader(); reader.onload = function () { const image = document.querySelector("#image"); image.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); } </script>
读取图片
<img id="image" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAAAAAAD">
2、Base64
btoa Binary-to-ASCII
atob ASCII-to-Binary
console.log(btoa('BC')); // QkM= console.log(atob('QkM=')); // BC
3、fetch API 从网络上获取图片
<img id="image" /> <script> const image = document.querySelector("#image"); fetch("https://avatars3.githubusercontent.com/u/4220799") .then((response) => response.blob()) .then((blob) => { const objectUrl = URL.createObjectURL(blob); image.src = objectUrl; }); </script>
读取图片
<img id="image" src="blob:http://127.0.0.1:5500/83dcb9c8-ffd3-4b5d-98a5-e3f6ff890bf2">
Blob(Binary Large Object)表示二进制类型的大对象
const blob = new Blob(['hello'])
参考