我有一个 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/