Skip to content

Instantly share code, notes, and snippets.

@compulim
Last active May 28, 2021 14:22
Show Gist options
  • Save compulim/5309fc95ea6e8440ac0333dc236b2d95 to your computer and use it in GitHub Desktop.
Save compulim/5309fc95ea6e8440ac0333dc236b2d95 to your computer and use it in GitHub Desktop.
Image to `console.log`
// Inspired from https://github.com/adriancooney/console.image
async function getBlobURL(base64) {
const res = await fetch(`data:image/png;base64,${base64}`);
const blob = await res.blob();
return URL.createObjectURL(blob);
}
async function getImageSize(url) {
return new Promise((resolve, reject) => {
const imageElement = document.createElement('img');
imageElement.onerror = ({ error }) => reject(error);
imageElement.onload = () => resolve({ height: imageElement.naturalHeight, width: imageElement.naturalWidth });
imageElement.setAttribute('src', url);
});
}
async function imageAsLog(base64, scale = 1) {
const url = await getBlobURL(base64);
const { height, width } = await getImageSize(url);
const scaledHeight = height * scale;
const scaledWidth = width * scale;
return [
`${width} × ${height}\n${url}\n%cM`,
`background-image: url(data:image/png;base64,${base64}); background-repeat: no-repeat; background-size: ${scaledWidth}px ${scaledHeight}px; color: Transparent; font-size: 1px; padding: ${
scaledHeight >> 1
}px; ${scaledWidth >> 1}px;`
];
}
// Reason why this is not logging out directly:
// - Dev may want to use console.group to hide the image, async console.log is not working for them.
console.log(...await imageAsLog(base64OfYourImage, 0.5));
@compulim
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment