How to use imagemagick in Ruby

Using imagemagick is quite straightforward, here is how:

1
2
sudo apt-get install libmagickwand-dev imagemagick
gem install rmagick

The Ruby code:

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
38
39
40
41
42
require 'rmagick'
class ImageProcessor
def self.resize(srcimg,tgtimg,width,height)
img = Magick::Image.read(srcimg).first
target = Magick::Image.new(width, height) do
#self.background_color = 'white'
end
img.resize_to_fit!(width, height)
target.composite(img, Magick::CenterGravity, Magick::CopyCompositeOp).write(tgtimg)
end
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! make tgtimg is PNG to be loseless
def self.scale(srcimg,tgtimg,width,height)
img = Magick::Image.read(srcimg).first
target = Magick::Image.new(width, height) do
#self.background_color = 'white'
end
img.scale!(width, height)
target.composite(img, Magick::CenterGravity, Magick::CopyCompositeOp).write(tgtimg)
end
def self.scale_width_only(srcimg,tgtimg,width)
img = Magick::Image.read(srcimg).first
x = img.columns
y = img.rows
ratio = (1.0*x)/y
height = width / ratio
target = Magick::Image.new(width, height)
target.composite(img, Magick::CenterGravity, Magick::CopyCompositeOp).write(tgtimg)
end
end
ImageProcessor.resize("test.png","test_resize1.png", 100, 60)
ImageProcessor.resize("test.png","test_resize2.png", 200, 400)
ImageProcessor.scale("test.png","test_scale1.png", 100, 60)
ImageProcessor.scale("test.png","test_scale2.png", 200, 400)
ImageProcessor.scale_width_only("test.png","test_scale3.png", 200)
Share