Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 66 lines (47 sloc) 1.878 kb
3151aab New example
rmagick authored
1 require 'RMagick'
2 include Magick
3
4 puts <<END_INFO
5
6 This example demonstrates how to make a thumbnail of an image.
ef19e57 Clean up comments
rmagick authored
7 An image is resized to the target size (retaining its original
8 aspect ratio, of course) and then "mounted" on a square background
9 with raised edges.
10
3151aab New example
rmagick authored
11 Usage:
12
13 ruby thumbnail.rb <filename <size>>
14
15 where `filename' is the name of an image file and `size' is the
16 size of the thumbnail in pixels. The default size is 120 pixels.
17 If you don't specify any arguments this script uses a default
18 image.
19
20 END_INFO
21
22 DEFAULT_SIZE = 120
23
24 case ARGV.length
25 when 2
26 size = ARGV[1].to_i
27 image = ARGV[0]
28 when 1
29 image = ARGV[0]
30 size = DEFAULT_SIZE
31 else
32 size = DEFAULT_SIZE
33 image = "../doc/ex/images/Blonde_with_dog.jpg"
34 end
35
36 geom = "#{size}x#{size}"
37
ef19e57 Clean up comments
rmagick authored
38 # Read the image and resize it. The `change_geometry' method
39 # computes the new image geometry and yields to a block. The
40 # return value of the block is the return value of the method.
3151aab New example
rmagick authored
41
42 img = Image.read(image)[0]
43 img = img.change_geometry(geom) { |cols, rows| img.thumbnail(cols, rows) }
44
45 # We need a background to display the thumbnail.
46 # Create a square, neutral gray background with raised edges.
47 # Make this background slightly larger than the image to allow
48 # for the raised border. A 3-pixel raised edge means that the
49 # background needs to be 6 pixels larger in each dimension.
50
51 bg = Image.new(size+6, size+6) { self.background_color = "gray75" }
52 bg = bg.raise(3,3)
53
54 # Just for the purposes of this example, display the thumbnail background on
55 # a larger white background.
56
57 white_bg = Image.new(size+50, size+50) {self.background_color = "white"}
58 white_bg = white_bg.composite(bg, CenterGravity, OverCompositeOp)
59
60 # Finally, center the thumbnail on the gray background.
61 thumbnail = white_bg.composite(img, CenterGravity, OverCompositeOp)
62
63 thumbnail.display
64 exit
65
Something went wrong with that request. Please try again.