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 = Image.read(file).first  
  img.trim!
  img.resize_to_fit!(110, 155)

  background = Magick::Image.new(110, 155) do
    self.background_color = 'none'
  end

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

  img.write("PATH_TO_PROCESSED_FOLDER/#{File.basename(file)}")
end

Image.read

As you can see Image.read 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.

trim!

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

resize_to_fit!

This method speaks for itself.

Image.new

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

composite

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

#resize #rmagick