Log images to the DevTools Console with console.image()

One of the things you can do on the DevTools’s Console is style the output for console.log() and the like:

console.log("%cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");

Leveraging this technique, it’s possible to log images to the console:

  1. Load the image via JS and extract its dimensions
  2. Expand the box of the logged message by adjusting the padding
  3. Set the image as the background-image

In code:

function getBox(width, height) {
    return {
        string: "+",
        style: "font-size: 1px; padding: " + Math.floor(height/2) + "px " + Math.floor(width/2) + "px; line-height: " + height + "px;"
    }
}

console.image = function(url, scale) {
    scale = scale || 1;
    var img = new Image();

    img.onload = function() {
        var dim = getBox(this.width * scale, this.height * scale);
        console.log("%c" + dim.string, dim.style + "background: url(" + url + "); background-size: " + (this.width * scale) + "px " + (this.height * scale) + "px; color: transparent;");
    };

    img.src = url;
};

Clever!

Adrian Cooney poored it into a library, which is also capable of auto-generating meme-like images on the console.

console.image()

(via Stefan)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.