Last active
February 21, 2017 22:20
-
-
Save saml/067edc31db00791be7131b614bca5b64 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ImageMagick MONO format encoder. | |
* | |
* https://www.imagemagick.org/script/formats.php | |
* Bi-level bitmap in least-significant-byte first order | |
* | |
* Turning 8 bytes to 1 byte (least significant bit first): | |
* 00 ff ff ff ff ff ff ff => 01111111 => 111111110 | |
* @param greyscaleBuffer | |
* @returns {Buffer} | |
*/ | |
function asMono(greyscaleBuffer) { | |
const bitsInBytes = 8; | |
const bytes = greyscaleBuffer.length; | |
const resultSize = bytes / bitsInBytes; | |
const result = new Buffer(resultSize); | |
for (let i = 0; i < resultSize; i++) { | |
let byte = 0x00; | |
const start = i * bitsInBytes; | |
const end = start + bitsInBytes - 1; | |
// 8 bytes to a byte, reversed | |
for (let j = end; j >= start; j--) { | |
// greyscale to 0 or 1 | |
const bit = greyscaleBuffer[j] >= 128 ? 0x1 : 0x0; | |
byte = (byte << 1) | bit; | |
} | |
result[i] = byte; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment