我正在使用流行的库(例如 axios)从网络上随机获取几张 PNG 图像。和 request但两者似乎都返回了错误的文件签名。
请以下面的片段为例(https://repl.it/@phobos/Request-png-file-wrong-buffer):
const request = require('request');
const png = require('pngjs').PNG;
const url = 'https://www.sample-videos.com/img/Sample-png-image-100kb.png';
function getPngBuffer() {
return new Promise((resolve, reject) => {
request.get(url, (err, res, body) => {
if (err || !body) return reject(err || new Error('no body'));
const buf = Buffer.from(body);
console.log('\nGOT SIG: ', buf.slice(0, 8));
console.log('EXPECTED SIG:', '<Buffer 89 50 4e 47 0d 0a 1a 0a>\n')
new png({ filterType:4 }).parse(buf, (err, png) => {
if (err) return reject(err);
return resolve('Worked!')
});
});
})
}
getPngBuffer()
.then(console.log)
.catch(console.error);
当我请求任意 PNG 图像并通过 Buffer API 查看最开始的字符时,我看到了错误的值。
根据 png 规范,它应该是 89 50 4e 47 0d 0a 1a 0a
,事实上,如果我通过浏览器下载图像并通过十六进制编辑器检查它确实是这样。
当我登录 buf
时,它会给我 ef bf bd 50 4e 47 0d 0a
。
本质上,它返回 o?=PNG
而不是 âPNG
,这会破坏 pngjs
之类的东西。
解决这个明显问题的最佳方法是什么,我真的不想改变 buf
来为它提供预期的文件签名,因为我还必须改变 CRC。
提前致谢
最佳答案
问题是编码问题,如果不设置编码,默认为 utf8
并且 body
将被转换为字符串。
只需将 encoding: null
传递给请求,然后删除 Buffer.from
因为 body
已经是一个缓冲区。
encoding - encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default). (Note: if you expect binary data, you should set encoding: null.)
const options = {
url: url,
encoding: null
};
request.get(options, (err, res, buf) => {
if (err || !buf) return reject(err || new Error('no body'));
console.log('\nGOT SIG: ', buf.slice(0, 8));
console.log('EXPECTED SIG:', '<Buffer 89 50 4e 47 0d 0a 1a 0a>\n')
new png({ filterType:4 }).parse(buf, (err, png) => {
if (err) return reject(err);
return resolve('Worked!')
});
});
关于node.js - 获取 PNG 图像时出现意外的缓冲区结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50910874/