Sunday, 13 October 2013

Retina Images

Retina Images


On my recent project I got introduced to the concept of images that need to be used for retina devices. Basically it is an image that has twice as many pixels as the original image.

Converting Images


The convention for having a retina image is to have a file with the word @2x in it. Since the project was only using these types of images I needed to generate non retina images (in other words normal images). Luckily for us there is this awesome tool called mogrify

So here are the instructions to get you going:
  • Install ImageMagick run: brew install ImageMagick
  • Copy your @2x images to a safe location like /tmp/images
  • To downsize your images run: mogrify -resize 50% -define png:format=png32 *.png
  • To then rename your new images by removing the @2x run:

    for file in *; do
        mv "$file" "${file/@2x/}"
    done
  • Copy your images back to the original folder.

Detecting Asset


Now that we have our assets converted we would like to detect which asset we would like to serve. This fortunately is pretty straightforward. All we need to do is detect from JavaScript (I prefer CoffeScript)

if window.devicePixelRatio == 2 
  # Server your @2x asset
else
  # Server your normal asset

That is it. I know I will use this technique in the future and hopefully you will too.