我正在嘗試在我的反應應用程式中使用 Base64 編碼的影像。
目前我從一個檔案夾加載影像,看起來像這樣:
<img className="..." src={imageFile}></img>
我想使用base64編碼的影像,我想我可以這樣做:
<img className="..." src={"data:image/svg xml;base64,PHN2ZyB4bWxucz0iaH...."}></img>
問題是 base64 字串很大,出于某種原因,我無法將它們存盤在我的組件中。我嘗試將它們放在一個 txt 檔案中并執行以下操作:
fs.readFile('image.txt', function(err, data){console.log(data);})
但我得到了大量的錯誤,包括:
Uncaught TypeError: fs.readFile is not a function
其中。
任何想法如何將base64字串存盤在單獨的檔案中并將它們加載到我的組件中?
謝謝!
uj5u.com熱心網友回復:
使用 Buffer 解碼 base64
let [imgSrc,setImgSrc] = useState('')
//
let base64_to_imgsrc = Buffer.from(base64String, "base64").toString()
//add the string to the state
setImgSrc(base64_to_imgsrc)
并像這樣使用它
<img src={"data:image/jpeg;base64," imgSrc} />
uj5u.com熱心網友回復:
您可以使用變數來存盤base64資料并將其匯出。
// filename.js
const image = "data:image/svg xml;base64,PHN2ZyB4bWxucz0iaH....";
export default image;
// import
import image from 'filename';
uj5u.com熱心網友回復:
有三種方法可以做到這一點,withFileReader和 with fetch,最簡單的方法是匯入它。
帶進口
import Base64JSON from "./readme.json";
console.log(Base64JSON);
使用檔案閱讀器
const readFile = async (json) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
const blob = new Blob([JSON.stringify(json)]);
reader.onload = async (e) => resolve(JSON.parse(e.target.result));
reader.readAsText(blob);
});
使用 Fetch
const readFileUsingHttp = async (path) => {
const json = await fetch(path);
return json.json();
};
這是顯示所有技術的沙盒 URL。
Codesandbox:https ://codesandbox.io/s/eager-golick-uvtcnh?file=/src/App.js
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435951.html
標籤:javascript 反应 图片 base64
上一篇:像素格式位位元組序
