如何將圖片轉換為資料 URI 字串

我在檔案系統中有一個圖片檔案,我想要使用資料 URI 格式將它放入 HTML 頁面中,以便將其嵌入到頁面本身中。 以下是我這樣做的方法: const imageData = fs.readFileSync(fileLocation, 'binary') const src = `data:${contentType};base64,${Buffer.from( imageData, 'binary' ).toString('base64')}` 在我的情況下,我只是從網路上下載圖片,所以我從回應標頭中取得了 contentType: const contentType = response.headers['content-type'] 最後,我可以在 img 標籤中使用 src,像這樣:<img src={src} />