node.js - 在 Node.js 中将二进制字符串转换为缓冲区

标签 node.js mongodb binary mongoose

我有一个 Web 服务,它采用表示图像的 base 64 编码字符串,使用 imagemagick 库创建该图像的缩略图,然后将它们都存储在 mongodb 中。我正在使用以下代码(大约)执行此操作:

var buf = new Buffer(req.body.data, "base64"); //original image

im.resize({ srcData: buf, width: 256 }, function(err, stdout, stderr) {
    this.thumbnail = new Buffer(stdout, "binary");
    //store buf and stdout in mongo
});

您会注意到我正在使用“二进制”编码创建一个 Buffer 对象,docs说不做:

'binary' - A way of encoding raw binary data into strings by using only the first 8 bits of each character. This encoding method is deprecated and should be avoided in favor of Buffer objects where possible. This encoding will be removed in future versions of Node.

首先,我不确定他们在那里说的是什么。我正在尝试创建一个 Buffer 对象,他们似乎暗示我应该已经有一个了。

其次,问题的根源似乎是 imagemagick 调整大小方法返回包含二进制数据的字符串。执行 typedef(stdout) 返回“字符串”并将其打印到屏幕上肯定会显示一堆非字符数据。

那我在这里做什么呢?我无法更改 imagemagick 的工作方式。有没有其他方法可以做我想做的事情?

最佳答案

这就是我如何成功地做同样的事情,将图像存储在 mongodb 中。

//original ---> base64
var thumbnail = new Buffer(req.body.data).toString('base64');
//you can store this string value in a mongoose model property, and save to mongodb

//base64 ---> image
var buffer = new Buffer(thumbnail, "base64");

我不确定将图像存储为 base64 是否是最好的方式

关于node.js - 在 Node.js 中将二进制字符串转换为缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13336324/

相关文章:

javascript - 使用 Node/TMI.js 命令的冷却时间

node.js - 强制 Heroku 将 App 视为 Node.js

node.js - 有没有办法让它有可能的冷却时间

mongodb - 重新创建 MongoDB 容器不会重新运行 docker-entrypoint-initdb.d 中的 config.js 文件

mongodb - 确保云中 MongoDB 传输的安全

node.js - Mongoose 根据经纬度信息和文本索引对文档进行排序

node.js - elastic beanstalk t2 服务器在哪里存储我的 node.js 应用程序文件?

c - 下面的二叉搜索树插入方法有什么问题?

c++ - 在不使用 + 或 - 的情况下添加二进制整数

binary - 以可变数量填充 elixir 中的二进制文件