xxxxxxxxxx
129
let img;
let workingString = "Lorem ipso fuck my hair's on fire";
function preload()
{
img = loadImage("DeleteSoon.png");
}
function setup()
{
createCanvas(img.width, img.height);
Encode();
Decode();
}
function Encode()
{
img.loadPixels();
EncodeString(workingString, img.pixels);
img.updatePixels();
image(img, 0, 0);
// saveCanvas();
}
function Decode()
{
img.loadPixels();
workingString = DecodeImage(img.pixels);
print(workingString);
image(img, 0, 0);
}
function EncodeString(s, pixelArray)
{
let outOfRoom = false;
for (let i = 0; i < s.length && 2 * 4 * (i + 1) < pixelArray.length; ++i)
{
let code = s.charCodeAt(i);
let loPixelIndex = 2 * 4 * (i + 0);
let hiPixelIndex = 2 * 4 * (i + 1);
EncodeCharacter(code, pixelArray, loPixelIndex, hiPixelIndex);
}
let nullIndexLo = s.length * 8;
let nullIndexHi = nullIndexLo + 8;
if (nullIndexHi + 3 < pixelArray.length)
EncodeCharacter(0, pixelArray, nullIndexLo, nullIndexHi);
}
function EncodeCharacter(code, pixelArray, loPixelIndex, hiPixelIndex)
{
let bits01 = (code & 0b00000011) >> 0;
let bits23 = (code & 0b00001100) >> 2;
let bits45 = (code & 0b00110000) >> 4;
let bits67 = (code & 0b11000000) >> 6;
WritePixel(pixelArray, loPixelIndex, bits01, bits23);
WritePixel(pixelArray, hiPixelIndex, bits45, bits67);
}
function WritePixel(pixelArray, pixelIndex, rBits, bBits)
{
let r = pixelArray[pixelIndex + 0];
let b = pixelArray[pixelIndex + 2];
pixelArray[pixelIndex + 0] = (r & ~0b11) | rBits;
pixelArray[pixelIndex + 2] = (b & ~0b11) | bBits;
}
function DecodeImage(pixelArray)
{
let output = "";
for (let i = 0; i < pixelArray.length; i += 8)
{
let loPixelIndex = i + 0;
let hiPixelIndex = i + 4;
let newChar = BuildChar(pixelArray, loPixelIndex, hiPixelIndex);
if (newChar === null)
{
print(`Reached null after ${output.length} chars`);
break;
}
output += newChar;
}
return output;
}
function BuildChar(pixelArray, loPixelIndex, hiPixelIndex)
{
let loBits = DecodePixel(pixelArray, loPixelIndex) << 0;
let hiBits = DecodePixel(pixelArray, hiPixelIndex) << 4;
let code = loBits | hiBits;
if (code === 0)
return null;
return String.fromCharCode(code);
}
function DecodePixel(pixelArray, pixelIndex)
{
let r = pixelArray[pixelIndex + 0];
let b = pixelArray[pixelIndex + 2];
let rBits = (r & 0b11) << 0;
let bBits = (b & 0b11) << 2;
return rBits | bBits;
}