I'm trying to read a pixel color (RGB) from a 2x2
bmp file (72 bytes) where the 1st pixel color is #ffc90e
:
The pixel color (BGR) starts at the position 62
.
So I'm trying to get that pixel color from nodeJS with the code below but I'm getting the wrong hex values. I've already tried changing the readFileSync
params to binary
and utf-8
. With utf-8 it gets closer but not accurate.
'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)
The output is:
Which may vary if I change readFileSync
param to binary
or utf-8
. But never accurate values are shown, although I can see them with an hex editor @ position 62
(picture above).
References:
https://nodejs.org/api/buffer.html
List of encodings that Node.js supports
UPDATE
I have tried different hex editors and all of them can read the correct binary data. Only node.js can't. Even this trivial hex editor can read it right but node.js can't:
I bet all my coins it is a node.js issue. (v12.16.2)
const fs = require('fs');
fs.readFile('color.bmp', (err, data) => {
console.log([...data])
})
Output:
[
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
]
Note the 14, 201, 255 near the end. That corresponds with ff, c9, 0e
for a 2x2 pixel image with the top left pixel the same yellow as you specified, and the rest white.
You can also use this module https://www.npmjs.com/package/bmp-js