Skip to content

Instantly share code, notes, and snippets.

@adrian154
Created June 14, 2022 19:19
Show Gist options
  • Select an option

  • Save adrian154/8bd54d4a1aa9e39372292fd9cae5129c to your computer and use it in GitHub Desktop.

Select an option

Save adrian154/8bd54d4a1aa9e39372292fd9cae5129c to your computer and use it in GitHub Desktop.
const sharp = require("sharp");
(async () => {
const img = sharp("test.png");
const meta = await img.metadata();
const raw = await img.raw().toBuffer();
const out = Buffer.alloc(meta.width * meta.height * 3);
for(let x = 0; x < meta.width; x++) {
for(let y = 0; y < meta.height; y++) {
const idx = (y * meta.width + x) * 3;
const r = raw[idx], g = raw[idx + 1], b = raw[idx + 2];
//const Y = 0.299*r + 0.587*g + 0.114*b;
Y = 128;
//const cb = -0.1687*r - 0.3313*g + 0.5*b + 128;
cb = 128;
const cr = 0.5*r - 0.4187*g - 0.0813*b + 128;
//out[idx] = out[idx + 1] = out[idx + 2] = Y;
out[idx] = Y + 1.402*(cr-128);
out[idx + 1] = Y - 0.34414 * (cb-128) - 0.71414 * (cr-128);
out[idx + 2] = Y + 1.772*(cb - 128);
}
}
await sharp(out, {raw: {width: meta.width, height: meta.height, channels: 3}}).png().toFile("y.png");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment