繁体   English   中英

从服务器获取图像文件并使用 nodejs express.js 将其转换为 base64

[英]Getting the image file from the server and converting it to base64 using nodejs express.js

如何创建一个 function,它从服务器获取准确的图像文件,然后将其转换为 base 64,最后将其存储到一个变量中。

注意:精确的图像文件(无需遍历目录以列出所有文件)。

您可以使用image-to-base64库来做到这一点。

安装

npm i image-to-base64

用法

const imageToBase64 = require('image-to-base64');
//or
//import imageToBase64 from 'image-to-base64/browser';

imageToBase64("path/to/file.jpg") // Path to the image
    .then(
        (response) => {
            console.log(response); // "cGF0aC90by9maWxlLmpwZw=="
        }
    )
    .catch(
        (error) => {
            console.log(error); // Logs an error if there was one
        }
    )

使用 base64 显示图像

<img src="data:image/jpg;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM