Common Tasks

Table of Contents

Getting information about an image

One of the most fundamental operations on an image is simply getting basic information about the image. RMagick assigns dozens of attributes to an image. All you have to do is read the image and then call the attribute methods. Here's a Ruby program that takes image filenames from the command line and then prints a variety of information about each image to the terminal.

require 'RMagick'
ARGV.each { |file|
    puts file
    img = Magick::Image::read(file).first
    puts "   Format: #{img.format}"
    puts "   Geometry: #{img.columns}x#{img.rows}"
    puts "   Class: " + case img.class_type
                            when Magick::DirectClass
                                "DirectClass"
                            when Magick::PseudoClass
                                "PseudoClass"
                        end
    puts "   Depth: #{img.depth} bits-per-pixel"
    puts "   Colors: #{img.number_colors}"
    puts "   Filesize: #{img.filesize}"
    puts "   Resolution: #{img.x_resolution.to_i}x#{img.y_resolution.to_i} "+
        "pixels/#{img.units == Magick::PixelsPerInchResolution ?
        "inch" : "centimeter"}"
    if img.properties.length > 0
        puts "   Properties:"
        img.properties { |name,value|
            puts %Q|      #{name} = "#{value}"|
        }
    end
    }

Converting an image to another format

Converting an image to another format is as simple as writing the image to a file. ×Magick uses the output filename suffix (".jpg" for JPEG, ".gif" for GIF, for example) or prefix ("ps:" for PostScript, for example) to determine the format of the output image.

Making thumbnails

RMagick gives you four different methods for resizing an image: resize, sample, scale, and thumbnail. All four are equally easy to use. Specify the number of columns and rows you want the thumbnail to have, like this:

img = Image.new "bigimage.gif"
thumb = img.scale(125, 125)
thumb.write "thumb.gif"

Alternatively, just pass a single Float argument that represents the change in size. For example, to proportionally reduce the size of an image to 25% of its original size, do this:

img = Image.new "bigimage.gif"
thumb = img.scale(0.25)
thumb.write "thumb.gif"

The resize method gives you more control by allowing you to specify a filter to use when scaling the image. Some filters produce a better-looking thumbnail at the expense of extra processing time. You can also use a blur argument, which specifies how much blurriness or sharpness the resize method should introduce.

The sample method, unlike the other two, does not do any color interpolation when resizing.

The thumbnail method is faster than resize if the thumbnail is less than 10% of the size of the original image.

flickr-style thumbnails

flickr thumbnails are 75 pixels wide and 75 pixels tall. If the original image isn't square, the thumbnail is cropped in its larger dimension so that the image isn't distorted. You can get make this kind of thumbnail with the resize_to_fill method.

thumb = img.resize_to_fill(75, 75)

Resizing to a maximum (or minimum) size

Say you need to make all your thumbnails no bigger than 64x64 but with the same aspect ratio as the original. Or, you don't want to resize the image if it's already smaller than 64x64. The change_geometry method can help.

The change_geometry method accepts an ×Magick geometry string argument and a block. The geometry string specifies how to change the image's size: one or two numbers to specify the new size and optional flags to describe any constraints. The change_geometry method parses the geometry string and computes new width and height values. Then it calls the block, passing the values it computed.

Within the block you can do whatever you want with the new values. Typically you'll call one of the resize methods mentioned in the previous section and make the resized image the return value from the block. The change_geometry method then returns that value to its caller.

Simple thumbnails

If you just want to make sure your thumbnail is no bigger than a certain width and height, use the resize_to_fit method.

thumb = img.resize_to_fit(75, 75)

Writing to or reading from a string instead of a file

Use the Image.from_blob method to construct an Image object from a string. Use the Image#to_blob method to convert an image to a string. A blob is simply an in-memory version of an image file. That is, you could use File.read to read an JPEG file into a string, then create an image by using that string as an argument to from_blob. Similarly, if you create a string version of an image with to_blob, then write the string to a file, any image viewer will be able to display it just as if you had written the image directly to a file. Blobs are very useful in web applications when you want to modify an image and then stream it back to the client.

Use Image#import_pixels to load pixel data from a string buffer into an image. The pixel data must be in scanline order, right-to-left and top-to-bottom. The data can be packed as 8-bit bytes, 16-bit halfwords, 32-bit fullwords, or as C floats or doubles. The reciprocal method is Image#export_pixels_to_str.

Converting a color image to grayscale

Use the quantize method with the Magick::GRAYColorspace argument. If you want real "grayscale," quantize the image to 256 colors. If you want to convert a color image to black-and-white, use 2 colors. (See the demo.rb example.)

Compressing image files

Many image formats, including JPEG, PDF, and BMP, support compressed image files. The type of compression used depends on the format. Specify the compression type by assigning a CompressionType value to the compression optional argument to the write method.

The JPEGCompression and ZipCompression types support multiple levels of compression. Use the quality optional argument to the write method. The quality attribute is a number between 0 and 100, with 100 representing the least compression. When you compress an image using JPEGCompression, more compression usually results in a lower-quality image. When you compress an image using ZipCompression, more compression usually takes longer.

For more information, see the ×Magick documentation for the -quality option to the utility commands.

img.write("myimage.jpg") { self.quality = 50 }

Making a drop shadow

Here's one way to make a drop shadow behind text. Make the shadow first by drawing the text in a light gray color. Position the text slightly to the right and down from where the real text will be. Then use the blur_image method to make the shadow by blurring the text. Finally, draw the text again in whatever color you want. (Click the image to see the Ruby program that created it.)

drop shadow example