Generate Square Thmumblnail by mini_magick[Ruby]


In this article, I would like to show a sample code to generate square thumbnail image by using Minimagick
which is a Ruby wrapper for ImageMagic.

🐞 Installation

Add the gem to your Gemfile & run bundle install:

gem 'mini_magick'

😼 Ruby Code

In a sample source, I will show you following flow:

  • (1) Download Sample Image
  • (2) Cut out a square thumbnail image by using Minimagick
  • (3) Save Image to file
require 'open-uri'
require 'mini_magick'

class ImageOptimizer
class << self
def resize(content, width, height, quality, output_path)
img = MiniMagick::Image.read(content)
w_original = img[:width].to_f
h_original = img[:height].to_f

# check proportions
op_resize = if w_original * height < h_original * width
"#{width.to_i}x"
else
"x#{height.to_i}"
end

img.combine_options do |i|
i.resize(op_resize)
i.gravity(:center)
i.quality quality.to_s if quality.to_i > 1 && quality.to_i < 100
i.crop "#{width.to_i}x#{height.to_i}+0+0!"
end

img.write(output_path)
end
end
end

URL = "http://farm4.staticflickr.com/3319/3584524809_f791a000e0_z.jpg"
OUT_PUT_FILE_PATH = './out_thumb.jpg'
WIDTH = 300
HEIGHT = 300
QUALITY = 80

content = open(URL)
resized_content = ImageOptimizer.resize(content, WIDTH, HEIGHT, QUALITY, OUT_PUT_FILE_PATH)

So, it is operation confirmation.

Another dog

The above image(640x480) was converted to the following square image(300x300):

Happy Hacking!

😸 API Document

Documentation for minimagick/minimagick

🎃 Special Thanks

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!