Image Manipulation in Ruby

Resize an image

Install RMagick

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

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
end
ImageProcessor.resize("src.png","tgt.png", 100, 60)

Watermark

Watermark with image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
require 'rmagick'
img = Magick::Image.read("test.png").first
mark = Magick::Image.read("cc.jpg").first
mark.background_color = "Transparent"
# resize the watermark to 60% of the image we want to watermark
watermark = mark.resize_to_fit(img.rows * 0.6, img.columns * 0.6)
# rotate this mark by 45 degrees anticlockwise (optional)
watermark.rotate!(-45)
# add watermark with 40% opacity for watermark, 100% opacity for image and position is center
newimg = img.dissolve(watermark, 0.4, 1, Magick::CenterGravity)
new.write("watermark_img.jpg")

Watermark with text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
require 'rmagick'
img = Magick::Image.read("test.png").first
mark = Magick::Image.new(img.rows, img.columns) {self.background_color = "none"}
draw = Magick::Draw.new
draw.annotate(mark, 0, 0, 0, 0, "www.yuxifan.com") do
draw.gravity = Magick::CenterGravity
draw.pointsize = 50
draw.font_family = "Arial Mono" # set font
draw.fill = "black" # set text color
draw.stroke = "none" # remove stroke
end
mark = mark.rotate(-45)
img2 = img.watermark(mark, 0.2, 0.5, Magick::CenterGravity)
img2.write("text_watermark.jpg")

Watermark with both image and text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
require 'rmagick'
img = Magick::Image.read("test.png").first
mark = Magick::Image.new(img.rows, img.columns) {self.background_color = "none"}
draw = Magick::Draw.new
draw.annotate(mark, 0, 0, 0, 0, "www.yuxifan.com") do
draw.gravity = Magick::CenterGravity
draw.pointsize = 50
draw.font_family = "Arial"
draw.fill = "black" # set text color
draw.stroke = "none" # remove stroke
end
mark = mark.rotate(-45)
img2 = img.watermark(mark, 0.2, 0.5, Magick::CenterGravity)
markimg = Magick::Image.read("cc.jpg").first
markimg.background_color = "Transparent"
watermark = markimg.resize_to_fit(img2.rows * 0.3, img2.columns * 0.3)
img3 = img2.watermark(watermark, 0.2, 0.3, Magick::SouthEastGravity)
img3.write("watermark_txtimg.jpg")
Share