![](/img/trans.png)
[英]Can i apoint the src img attribute to a blob file or a base64 encoded image?
[英]How to display a base64 image that is inside a .txt file on the img src
A.txt 不是直接用作圖像 src 的受支持格式,因此這是不可能的。
如果your.txt里面的內容沒有變化,我建議直接使用base64作為圖片src。 你已經說過你做到了(這是有效的),所以只適用於那些不知道如何使用 base64 作為圖像 src 的人。 這是一個例子
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" />
然而,為了使用 txt 文件,您必須通過 Javascript 加載文件,獲取文件內容並將 base64 添加為圖像 src。 XMLHttpRequest將是獲取內容的一種方法。
const client = new XMLHttpRequest();
// instead of foo.txt you need to add your .txt file of course
client.open('GET', '/foo.txt');
client.onreadystatechange = () => {
// Make sure the request was done
if (client.readyState === XMLHttpRequest.DONE) {
const status = client.status;
// make sure the request ended up successfully
if (status === 0 || (status >= 200 && status < 400)) {
// If request was successful, grab the base64 from the response
const base64Image = client.responseText;
console.log(base64Image);
// add the base64 as image src
const image = document.querySelector('#loading');
image.src = base64Image;
} else {
// In case the request to get the .txt content failed, you can do something else.
// For example add a static fallback image
}
}
}
client.send();
另一個注意事項:可能存在客戶端或服務器端(或什至兩者)的處理能力非常低的情況。 例如在低端手機或共享 web 主機上。 所以你必須知道它可能需要一段時間才能顯示圖像,因為所有這些步驟都必須先運行:
因此,為了在所有圖像加載完成時不會出現損壞的圖像或閃爍,您可以在 html 中提供占位符圖像。 文件大小和 static 很小的東西。 只要image.src = base64Image;
運行,它將被替換。
但在你的情況下,它說的是“loader_gif”,所以我想它已經是一些加載動作了。 在通過 Javascript 加載加載程序圖像之前,擁有一個占位符圖像對於加載操作來說似乎有點“過分”。
您的用例與讓瀏覽器像加載任何其他資源一樣加載實際圖像並沒有太大區別。 我假設您已經考慮將圖像作為實際圖像。
因為圖像並不是真正的圖像,所以您需要對其進行管理。 在您的情況下,它“幾乎”是圖像格式,因此處理量很小,這意味着您只需要從文件中獲取數據並將其設置在圖像元素的 src 處。
<body>
<img id="loading" alt="Red dot" />
<script>
fetch('/assets/images/loader_gif.txt').then(response => response.text())
.then(b64img => {
document.getElementById('loading').src = b64img;
})
</script>
</body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.