Last active
March 15, 2020 21:54
-
-
Save scriptype/c4f2946a1ef9b48bdbbf5b9fdc0c02e1 to your computer and use it in GitHub Desktop.
Simplest image encoding ever: building binary strings from rgb values
This file contains hidden or 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
var randomInteger = (max = 1) => Math.round(Math.random() * max) | |
var nArrayOf = (n, ofWhat) => [...Array(n).keys()].map(ofWhat) | |
var zeroPad = (value = '', n = 8) => `${value}00000000`.slice(0, n) | |
var splitBy = (string = '', by = 8) => { | |
var result = [] | |
for (var i = 0; i < string.length; i += by) { | |
result.push(string.slice(i, i + by)) | |
} | |
return result | |
} | |
var splitArrayBy = (array = [], by = 1) => { | |
var result = [] | |
for (var i = 0; i < array.length; i += by) { | |
result.push(array.slice(i, i + by)) | |
} | |
return result | |
} | |
var columnCount = 500 + randomInteger(500) | |
var rowCount = 500 + randomInteger(500) | |
var RGBMatrixGenerated = ( | |
nArrayOf(rowCount, () => ( | |
nArrayOf(columnCount, () => ( | |
nArrayOf(3, () => randomInteger(255)) | |
)) | |
)) | |
) | |
var binaryMatrix = RGBMatrixGenerated.map(row => ( | |
row.map(px => ( | |
px.map(bit => zeroPad(bit.toString(2))) | |
)) | |
)) | |
var binaryString = binaryMatrix.map(row => ( | |
row.map(px => ( | |
px.join('') | |
)).join('') | |
)).join('') | |
var recoveredBytes = splitBy(binaryString, 8) | |
var recoredBinaryMatrix = splitArrayBy(recoveredBytes, columnCount * 3).map(row => splitArrayBy(row, 3)) | |
console.log({ | |
width: columnCount, | |
height: rowCount, | |
binaryStringLength: `${binaryString.length / 1024}kb`, | |
binaryString | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment