[英]Convert <img src="phone.png"> to Base64 <img src="data:img/png;base64,...."> by compiling the app, to make the image load instantly with the app
這是一個獨特的問題:我不想使用瀏覽器 javascript 來解決這個問題,請繼續閱讀...
ng build
或ng serve
)將<img src="...">
為 Base64 img 標簽,以使圖像立即加載 - 除了應用程序本身之外無需進一步下載,但也使開發應用程序時圖像可動態更改。 例如,這是一個組件 - home.component.html
:
編譯前的代碼(注意 base64 指令,不過它只是一個想法):
<img src="assets/images/phone.png" base64>
編譯后需要的代碼:
<img src="data:image/png;base64,iVBORw0......rest-of-base-64-goes-here">
重要提示:這應該在用戶不運行前端 javascript 操作或調用圖像文件的情況下發生。 (也就是說,編譯時文件phone.png
甚至不存在)
我phone.png
在開發時編輯本地圖像phone.png
。
我知道我可以手動將文件轉換為 base64 並在我的組件中更新它,但這正是我不想做的 - 我希望它自動發生以節省時間。
這意味着圖像將位於組件本身中,位於已編譯的.js文件之一中,因此將立即與應用程序一起加載。
類似於<img src="phone.png base64>
**
我認為它可以以某種方式使用 node/webpack 來完成,但我不知道如何。
您需要使用readAsDataUrl()
function getBase64(event) {
let me = this;
let file = event.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//me.modelvalue = reader.result;
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
希望能幫到你。。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.