Last active
May 28, 2021 14:22
-
-
Save compulim/5309fc95ea6e8440ac0333dc236b2d95 to your computer and use it in GitHub Desktop.
Image to `console.log`
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
// 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)); |
Author
compulim
commented
May 12, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment