Skip to content

Instantly share code, notes, and snippets.

@OrionReed
Last active June 28, 2024 17:33
Show Gist options
  • Save OrionReed/7f5310266b2e1b7b109ef6333031e9ce to your computer and use it in GitHub Desktop.
Save OrionReed/7f5310266b2e1b7b109ef6333031e9ce to your computer and use it in GitHub Desktop.
Log images or pixels to the console.
class console2 {
static image(url: string, size = 100) {
fetch(url)
.then((res) => res.blob())
.then((blob) => {
const reader = new FileReader();
reader.onloadend = () => {
const dataUrl = reader.result as string;
const style = [
'font-size: 1px;',
`padding: ${size}px ${size}px;`,
'background: url(' + dataUrl + ') no-repeat;',
'background-size: contain;'
].join(' ');
console.log('%c ', style);
};
reader.readAsDataURL(blob);
})
.catch((err) => {
console.error(err);
});
}
static pixels(pixels: number[][], size = 100) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (ctx) {
canvas.width = pixels[0].length;
canvas.height = pixels.length;
const imageData = ctx.createImageData(canvas.width, canvas.height);
for (let x = 0; x < pixels[0].length; x++) {
for (let y = 0; y < pixels.length; y++) {
const value = pixels[y][x]
const index = (y * canvas.width + x) * 4;
imageData.data[index] = value; // R
imageData.data[index + 1] = value; // G
imageData.data[index + 2] = value; // B
imageData.data[index + 3] = 255; // A
}
}
ctx.putImageData(imageData, 0, 0);
}
const dataURL = canvas.toDataURL();
const style = [
'font-size: 1px;',
`padding: ${size}px ${size}px;`,
'background: url(' + dataURL + ') no-repeat;',
'background-size: contain;',
].join(' ');
console.log('%c ', style);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment