Skip to content

Instantly share code, notes, and snippets.

@UlisesGascon
Created January 25, 2019 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UlisesGascon/771255a0340c219156cb53561599f6ab to your computer and use it in GitHub Desktop.
Save UlisesGascon/771255a0340c219156cb53561599f6ab to your computer and use it in GitHub Desktop.
Inversión Binaria de imagenes
// npm install jimp
const Jimp = require('jimp');
function reverseString(str) {
return str.split("").reverse().join("");
}
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
function bin2dec (bin){
return parseInt(bin, 2);
}
function convertToBinaryColor(colorDecimal){
const colorBinary = dec2bin(colorDecimal);
return colorBinary.padStart(8, '0');
}
function joinBinaryRGB(pixel){
return convertToBinaryColor(pixel.r) + convertToBinaryColor(pixel.g) + convertToBinaryColor(pixel.b);
}
function splitBinaryRGB(chunk){
return chunk.match(/.{8}/g);
}
function segmentsToJimpObj(segments, alpha){
return Jimp.rgbaToInt(bin2dec(segments[0]), bin2dec(segments[1]), bin2dec(segments[2]), alpha)
}
function replacePixel(img, width, height){
console.time("Pixel conversion");
const pixel = Jimp.intToRGBA(img.getPixelColor(width, height));
console.log(`[Current] Pixel ${width},${height}: ${pixel}`);
const binaryRGB = joinBinaryRGB(pixel);
console.log(`[Current] Pixel ${width},${height} | Binary: ${binaryRGB}`);
const reversedBinaryRBG = reverseString(binaryRGB);
console.log(`[Current] Pixel ${width},${height} | Reversed Binary: ${reversedBinaryRBG}`);
const segmentedBinaryRGB = splitBinaryRGB(reversedBinaryRBG);
console.log(`[Current] Pixel ${width},${height} | Reversed Binary Splitted: ${reversedBinaryRBG}`);
const pixelGenerated = segmentsToJimpObj(segmentedBinaryRGB, pixel.a);
console.log(`[Current] Pixel ${width},${height} | Final Data: ${pixelGenerated}`);
img.setPixelColor(pixelGenerated, width, height);
console.timeEnd("Pixel conversion");
console.log("--------------");
}
Jimp.read('img_original.jpg', (err, img) => {
if (err) throw err;
const originalWidth = img.bitmap.width;
const originalHeight = img.bitmap.height;
let currentWidth = 0;
let currentHeight = 0;
console.time("Image conversion")
for (currentWidth = 0; currentWidth < originalWidth; currentWidth++) {
for (currentHeight = 0; currentHeight < originalHeight; currentHeight++) {
replacePixel(img, currentWidth,currentHeight);
}
}
img.write('img_new.jpg');
console.timeEnd("Image conversion");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment