Imagemagick crop and center

October 12th, 2011. Tagged: images

Say you get a sprite created no matter how but the original images are long gone or for whatever reason not available. With imagemagick it's easy to crop them back. And I think it's easier and more precise than with a graphic UI, e.g. photoshop. Let's see how.

Task: get me a 16x16 favicon for yahoo when all you have is the Yahoo search page

  1. goto yahoo search, right click the icon, Inspect
  2. Download the sprite:
    $ curl http://a.l.yimg.com/pv/i/us/sch/gr5/metro_sprite_20110907.png > ys.png
    

    here it is:

  3. While inspecting the CSS you noticed
    width: 16px;
    height: 12px;
    background-position: -117px -95px;
    

    This helps us cut precisely as opposed to guess the coordinates

  4. Crop it:
    $ convert ys.png -crop 16x12+117+95 yfavicon.png
    

    The result is a 16x12 image:

  5. And because we have this arbitrary requirement that we want all favicons to be 16x16 because our design says so, let's resize it to fit a 16x16 box and center it inside the box
    $ convert yfavicon.png -background transparent -gravity center -extent 16x16 y.png
    

    Here:

  6. And just because, let's make it 160x160 with colored background to make sure the command works
    $ convert yfavicon.png -background orange -gravity center -extent 160x160 yorange.png
    

  7. Enjoy the rest of your day having saved some time by doing things on the command line instead of dealing with UI that gets in the way :)

Tell your friends about this post: Facebook, Twitter, Google+

6 Responses

  1. I’m surprised they’re still using that sprite! It’s almost the same as when I created it a few years ago, and still includes icons that aren’t even used anymore.

    For your next post, you should demonstrate how to remove unused portions of a sprite on the command line. ;)

  2. Yo Stoyan,

    This is pretty tight! Definitely a time saver. Thanks.

  3. Unrelated to spriting, but I couldn’t resist posting a link to my project powered by Imagemagik: http://www.favoriteiconsofinternet.com/

    I’m using it as an unusual example of performance optimization at NY Meet4SPEEDs. Still some way to go – next step is progressive enhancement for client side image maps ;)

  4. Nice article. it should also be possible in php and makes sprite more flexible. in this direction.

  5. I guess it is also possible to do this in Javascript with canvas :-)

    Paste a URL of an image in a html-page and some css-code and choose save-as-file.

    done.

  6. He jests at scars, that never felt a wound

Leave a Reply