从NodeJS中的.bmp文件读取二进制数据(像素颜色)

问题描述 投票:1回答:1

我正在尝试从2x2 bmp文件(72字节)中读取第一个像素颜色为#ffc90e的像素颜色(RGB):

像素颜色(BGR)从位置62开始。

enter image description here

因此,我尝试使用以下代码从nodeJS获取该像素颜色,但十六进制值错误。我已经尝试过将readFileSync参数更改为binaryutf-8。使用utf-8,距离更近但不准确。

'use strict'

const FS = require('fs') // https://nodejs.org/api/fs.html
process.chdir(__dirname)

var stream = new Buffer.from(FS.readFileSync('2x2.bmp', 'utf-8'))
console.log(stream)
console.log(stream.toJSON())

var blue = stream.toString('hex', 62, 63)
var green = stream.toString('hex', 64, 65)
var red = stream.toString('hex', 66, 67)

console.log(red, green, blue)

输出为:

enter image description here

如果将readFileSync参数更改为binaryutf-8,则可能会有所不同。但是,尽管我可以使用十六进制编辑器@ position 62(上图)看到它们,但从未显示出准确的值。

参考:

https://nodejs.org/api/buffer.html

List of encodings that Node.js supports

UPDATE

我尝试了不同的十六进制编辑器,它们都可以读取正确的二进制数据。只有node.js不能。即使this平凡的十六进制编辑器也可以正确读取,但node.js无法:

enter image description here

我敢打赌,这是一个node.js问题。 (v12.16.2)

node.js binaryfiles
1个回答
1
投票
const fs = require('fs');
fs.readFile('color.bmp', (err, data) => {
    console.log([...data])
})

输出:

[
  66, 77,  70,   0,   0,   0,   0,   0,   0,   0,  54,   0,
   0,  0,  40,   0,   0,   0,   2,   0,   0,   0,   2,   0,
   0,  0,   1,   0,  24,   0,   0,   0,   0,   0,  16,   0,
   0,  0, 195,  14,   0,   0, 195,  14,   0,   0,   0,   0,
   0,  0,   0,   0,   0,   0, 255, 255, 255, 255, 255, 255,
   0,  0,  14, 201, 255, 255, 255, 255,   0,   0
]

请注意结尾处的14、201、255。对应于ff,c9,0e

对于一个2x2像素的图像,左上像素与您指定的黄色相同,其余为白色。

您也可以使用此模块https://www.npmjs.com/package/bmp-js

© www.soinside.com 2019 - 2024. All rights reserved.