Skip to content

Instantly share code, notes, and snippets.

@tscholl2
Last active August 19, 2020 14:38
Show Gist options
  • Select an option

  • Save tscholl2/bb7a03f71a7e22d2686e1039f285d9a7 to your computer and use it in GitHub Desktop.

Select an option

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