resizing icons

Today I faced a problem – given a set of ~70 icons I needed to resize them. But all images had different sizes (both width and height) so the task is not only resize, but crop them and center.

Of course one can write a Photoshop script to do that BUT with #ruby it could be done in a minute.

require 'RMagick'
include Magick

Dir['PATH_TO_FOLDER/*.png'].each do |file|
  img =  
  img.resize_to_fit!(110, 155)

  background =, 155) do
    self.background_color = 'none'

  img = background.composite(img, Magick::CenterGravity, Magick::OverCompositeOp)


As you can see returns an array of images. According to documentation

Note: Because an image file can contain multiple images or multiple image layers, read always returns an array containing 0 or more elements, one element for each image or image layer in the file.


This is where magic actually happens. It removes all borders of same color, so we left with rectangle which contains only image.


This method speaks for itself.

As you can see we don't pass any variable to block, this is a nice trick described in the article about Hipster Struct


This method allows us to center our cropped and resized image with blank background. Check out documentation for more options.

#resize #rmagick