繁体   English   中英

如何在sails.js 或通常在服务器端JavaScript 中将图像转换为base64 编码的数据URL?

[英]How do I convert an image to a base64-encoded data URL in sails.js or generally in the servers side JavaScript?

我正在sails.js制作一个小应用程序,我需要将图像存储在数据库中。 为此,我需要将图像转换为 base64 编码的数据 URL,以便我可以将其保存为我的帆模型中的字符串。 但是,我不知道如何将其转换为这种形式。 所有关于将图像转换为 base64 编码的数据 URL 的较旧问题都被问到,他们回答了关于在客户端执行此操作的问题。 但是,我想在服务器端执行此操作,同时我将通过发布请求获取图像。 我怎样才能做到这一点?

据我了解,您想将文件转换为 base64 编码的字符串。 文件是否是图像,这无关紧要。

var fs = require('fs');

// function to encode file data to base64 encoded string
function base64_encode(file) {
    // read binary data
    var bitmap = fs.readFileSync(file);
    // convert binary data to base64 encoded string
    return new Buffer(bitmap).toString('base64');
}

用法:

var base64str = base64_encode('kitten.jpg');

来源

它可以通过readFileSync实现,将图像路径作为第一个参数传递,将编码选项作为第二个参数传递。 如下图所示:

var fs = require('fs');

var imageAsBase64 = fs.readFileSync('./your-image.png', 'base64');

根据 节点文档:

fs.readFileSync(path[, options])

fs.readFile() 的同步版本。 返回路径的内容。

如果指定了编码选项,则此函数返回一个字符串。 否则它返回一个缓冲区。

//可以使用image-to-base64

const imageToBase64 = require('image-to-base64');

imageToBase64("URL") // insert image url here. 
    .then( (response) => {
          console.log(response);  // the response will be the string base64.
      }
    )
    .catch(
        (error) => {
            console.log(error);
        }
    )
//instala via npm
npm install --save image-to-uri

//declara no codigo
const imageToUri = require('image-to-uri');

//implementa 
let imagem = imageToUri("caminho da sua imagem");

这是另一种简单的方法,在列出图像时使用它

@{
    if (item.ImageData != null)
    {
        string imageBase64 = Convert.ToBase64String(item.ImageData);
        string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
        <img src="@imageSrc" width="100" height="100" />
    }
}

暂无
暂无

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

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