Last active
August 19, 2020 14:38
-
-
Save tscholl2/bb7a03f71a7e22d2686e1039f285d9a7 to your computer and use it in GitHub Desktop.
Some types of compression in js
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
| async function encode(input) { | |
| // TODO: handle unicode? | |
| const canvas = document.createElement("canvas"); | |
| canvas.width = Math.ceil(Math.sqrt(input.length / 3)); | |
| canvas.height = canvas.width; | |
| const ctx = canvas.getContext('2d'); | |
| const imgData = ctx.createImageData(canvas.width, canvas.height); | |
| for (let i = 0, j = 0; i < 7; i++) | |
| imgData.data[i] = i % 4 == 3 ? 255 : (input.length >>> (8 * j++)) & 0xff; | |
| for (let i = 7, j = 0; i < 4 * canvas.width * canvas.height; i++) | |
| imgData.data[i] = i % 4 == 3 ? 255 : input.charCodeAt(j++) || 0; | |
| ctx.putImageData(imgData, 0, 0); | |
| return canvas.toDataURL('image/png', 0); | |
| } | |
| async function decode(input) { | |
| const image = new Image(); | |
| image.src = input; | |
| await new Promise(r => image.onload = r); | |
| const canvas = document.createElement("canvas"); | |
| canvas.width = image.width; | |
| canvas.height = image.height; | |
| const ctx = canvas.getContext('2d'); | |
| ctx.drawImage(image, 0, 0); | |
| const imgData = ctx.getImageData(0, 0, image.width, image.height); | |
| let length = 0; | |
| for (let i = 0, j = 0; i < 7; i++) | |
| length |= i % 4 == 3 ? 0 : (imgData.data[i] << (8 * j++)); | |
| let output = ""; | |
| for (let i = 7; i < imgData.data.length; i++) | |
| output += i % 4 == 3 ? "" : String.fromCharCode(imgData.data[i]); | |
| return output.substr(0, length); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment