Quick Snippet: Tumblr Retina Avatars

July 2nd, 2012 • 1 note

I’ve been working on getting this blog looking nice on the new iPads, and one of the big tasks is getting the assets retina-ready. For the most part it was pretty easy, as this blog doesn’t use a lot of images. Background images just use the background-size property, while regular images are just set to half their width and height.

Tumblr notes are a little tricker though. Tumblr automatically renders out a 16px avatar for notes, and they sit on Tumblr servers. So how do we make these retina? Well, I discovered Tumblr actually stores multiple sizes of all user’s avatars. The url they use looks something along the lines of

http://24.media.tumblr.com/avatar_4dd2c3a88042_16.png

Go to the same link, and replace 16, with 32? No dice, just some weird access denied error. Let’s 48 instead. Bingo. Great! So we need to somehow switch that out. jQuery to the rescue!

$(document).ready(function () {
    $('img.avatar').attr("src", function () {
        return this.src.replace(/_16\.png/g, '_48.png');
    });
    $('img.avatar').one('error', function () {
        this.src = this.src.replace(/_48\.png/g, '_16.png');
    });
});

We’re using a bit of regex magic here to grab the source attribute of the images and replace 16 with 48. The next function is a fallback, because in my tests I found out that you can randomly get the same access error as the 32px attempt, with certain users. If it can’t find one, it’ll default back to the 16px non-retina version. 

Now, in your CSS, you just need to set the images height and width to at least half of what the current avatar size is. My blog’s avatars are 16px and they’re coming from a 48px source, so they’ll look nice and crisp on retina devices.

  1. collinh posted this