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 🙂

Comments? Feedback? Find me on Twitter, Mastodon, Bluesky, LinkedIn, Threads