Skip to content

Instantly share code, notes, and snippets.

@benib
Last active October 27, 2019 18:10
Show Gist options
  • Save benib/81e5b2f0c6bba52cd90c8af6403eb030 to your computer and use it in GitHub Desktop.
Save benib/81e5b2f0c6bba52cd90c8af6403eb030 to your computer and use it in GitHub Desktop.
Promote mostly black pixels to K only in a CMYK TIFF
function promoteTiffBufferToBlack(tiffBuffer) {
const ifds = UTIF.decode(tiffBuffer);
// tiff tag descriptions: https://www.loc.gov/preservation/digital/formats/content/tiff_tags.shtml
// tiff image file format: http://www.fileformat.info/format/tiff/corion.htm
const bitsPerSample = ifds[0].t258;
const stripOffsets = ifds[0].t273[0];
const stripByteCounts = ifds[0].t279[0];
// loop over the image in tiffBuffer to promote mostly black pixels to K only
for (
let i = stripOffsets; // start at the offset
i < stripOffsets + stripByteCounts; // keep going until we reach the end of the strip
i = i + bitsPerSample.length // seek by the amount of bitsPerSample sizes (this is 4 or 5, depending on the number of channels in the source image.)
) {
const cmyk = [
tiffBuffer[i], // C
tiffBuffer[i + 1], // M
tiffBuffer[i + 2], // Y
tiffBuffer[i + 3] // K
];
// if K (black) is the dominant channel, we set the others to 0
if (Math.max(...cmyk) === cmyk[3]) {
tiffBuffer[i] = 0; // C
tiffBuffer[i + 1] = 0; // M
tiffBuffer[i + 2] = 0; // Y
// add 5% additional black to the K channel in case we stripped the others
// but only if it is already pretty black
if (tiffBuffer[i + 3] > 150) {
tiffBuffer[i + 3] = Math.min(tiffBuffer[i + 3] + 255 / 20, 255);
}
}
}
return tiffBuffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment