Created
January 25, 2019 11:19
-
-
Save UlisesGascon/771255a0340c219156cb53561599f6ab to your computer and use it in GitHub Desktop.
Inversión Binaria de imagenes
This file contains 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
// 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