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:

1
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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