RMagick: class ImageList

###### RMagick User's Guide and Reference

# class ImageList < Array
mixes in Comparable

## class methods

### new

Magick::ImageList.new -> imagelist
Magick::ImageList.new(filename[, filename...]]) -> imagelist

#### Description

Creates a new imagelist. If one or more image filenames are specified, opens and reads the files, adding a new image for each image in the image file(s). Sets the scene number to the index of the last image, or `nil` if no filenames are specified.

#### Arguments

Zero or more image file names.

#### Returns

A new imagelist. The imagelist contains an Image object for each image in the specified files. A file can contain more than one image. For example, new will create an image for each frame in an animated GIF or each layer in a multi-layer Photoshop file.

#### Example

    i = Magick::ImageList.new
    i = Magick::ImageList.new("Button_A.gif", "Cheetah.jpg")

## attributes

### delay=

imagelist.delay=n

#### Description

In conjunction with ticks_per_second sets the length of time between each image in an animation. The `delay=` attribute assigns the same delay to all the images in the imagelist. Use Image#delay= to set different delay values on individual images.

#### Arguments

An integer value representing the number of ticks that must elapse between each image in an animation.

#### Returns

self

#### Example

    imagelist.delay = 20 # delay 1/5 of a second between images.

#### See also

Image#delay=

### iterations=

imagelist.iterations=n

#### Description

Sets the number of times an animated image should loop.

The animate method and the ImageMagick animate/GraphicsMagick gm utilities do not respect this number. Both will repeat the animation until you stop them. Mozilla (and presumably Netscape) do respect the value..

#### Arguments

The number of iterations.

#### Returns

self

#### Example

    imagelist.iterations = 10

### length

imagelist.length -> anInteger

#### Description

Returns the number of images in the imagelist.

#### Example

    i = Magick::ImageList.new("images/Button_A.gif", "images/Button_B.gif")
    i.length » 2

### scene, scene=

imagelist.scene -> anInteger
imagelist.scene = anInteger

#### Description

Get/set the current scene number. The scene number indicates the image to which Image methods are sent.

#### Example

    imagelist.scene = 10
    imagelist.scene » 10

### ticks_per_second=

imagelist.ticks_per_second = anInteger

#### Description

Used in conjunction with delay to establish the elapsed time between frames in an animation. By default the number of ticks per second is 100.

This attribute is available only in ImageMagick 6.2.4 and later. Prior to this release the number of ticks per second is fixed at 100.

#### Example

    imagelist.ticks_per_second = 1000

## instance methods

### Array methods

#### Description

`ImageList` is a subclass of `Array`, so you can manipulate the images in an imagelist using almost all of the methods defined in `Array`. Typically these methods also update the scene number. The scene number will never exceed the number of images in the list, and if the imagelist contains no images the scene number will be `nil`.

Array methods defined in the ImageList class that would normally return an array return an ImageList.

Most array methods keep the current image current. If the method moves the current image to a new position, the method updates the scene number to the new index. If the method deletes the current image, the scene number is set to the last image in the list. The following table lists the methods that do not follow these rules.

Array method behavior
Array method | scene number will be...
--- | ---
<< | set to index the last image in the list
clear | set to `nil`
concat | set to index the last image in the list
push | set to index the last image in the list
unshift | set to 0

Adding anything other than a image to an imagelist has undefined results. Most of the time RMagick will raise an ArgumentError exception.

The `assoc`, `flatten`, `flatten!`, `join`, `pack`, and `rassoc` methods are not defined in the ImageList class.

#### Example

Add noise to a model image. Append the resulting image to the imagelist in "example". (See the `demo.rb` example.)

    example = Magick::ImageList.new
    model = Magick::ImageList.new "model.miff"
    example << model.add_noise Magick::LaplacisanNoise

#### See also

scene, scene=

### <=>

imagelist <=> anOtherImageList -> -1, 0, 1

#### Description

Compares two imagelists and returns -1, 0, or 1 if the receiver is less than, equal to, or greater than the other imagelist. The comparison between the receiver (a) and the other (b) is performed this way:

1. For all images `n`, if the result of `a[n] <=> b[n]` is not 0 then that is the result of a <=> b. Individual images are compared by comparing their signatures.
2. If `a.scene <=> b.scene` is not 0, returns the result
3. Returns `a.length <=> b.length`

`ImageList` mixes in the `Comparable` module.

#### See also

Image#<=>, signature

### animate

imagelist.animate([delay]) [ { optional arguments } ] -> self

#### Description

Animate the images to an X Window screen. By default displays to the local screen. You can specify a different screen by assigning the name to the `server_name` attribute in the optional arguments block.

#### Returns

self

#### Example

    imagelist.animate
    imagelist.animate { self.server_name = "other:0.0" }

#### See also

display

#### Note

The animate method is not supported on native MS Windows.

#### Magick API

AnimateImages

### append

imagelist.append(`true` or `false`) -> anImage

#### Description

Append all the images in the imagelist, either vertically or horizontally. If the images are not of the same width, any narrow images will be expanded to fit using the background color.

#### Arguments

If `true`, rectangular images are stacked top-to-bottom, otherwise left-to-right.

#### Returns

A image composed of all the images in the imagelist.

#### Example

See the map example.

#### Magick API

AppendImages

### average

imagelist.average -> anImage

#### Description

Averages all the images together. Each image in the image must have the same width and height.

#### Returns

A single image representing the average of all the images in the imagelist.

#### Example

#### Magick API

AverageImages

### clone

imagelist.clone -> anImageList

#### Description

Same as dup, but the frozen state of the original is propogated to the copy.

#### Returns

A new imagelist

#### See also

copy

### coalesce

imagelist.coalesce -> anImageList

#### Description

Merges all the images in the imagelist into a new imagelist. Each image in the new imagelist is formed by flattening all the previous images.

The length of time between images in the new image is specified by the delay attribute of the input image. The position of the image on the merged images is specified by the page attribute of the input image.

#### Returns

A new imagelist

#### Example

This example is an animated GIF created by coalescing 25 small images in a grid. Mouse over the image to start the animation.

#### See also

flatten_images

#### Magick API

CoalesceImages

### copy

imagelist.copy -> anImageList

#### Description

Creates a deep copy of the imagelist. The new imagelist contains a copy of all the images in the original imagelist.

#### Returns

An imagelist

#### Example

    imagelist2 = imagelist1.copy

#### See also

Image#copy, clone, dup

### cur_image

imagelist.cur_image -> anImage

#### Description

Retrieves the image indexed by scene. Raises `IndexError` if there are no images in the list.

Both the ImageList class and the Image class support the `cur_image` method. Of course, in the Image class, `cur_image` simply returns `self`. When a method accepts either an image or a imagelist as an argument, it sends the `cur_image` method to the argument to get the current image.

#### Returns

An image

### deconstruct

imagelist.deconstruct -> anImageList

#### Description

This method constructs a new imagelist containing images that include only the changed pixels between each image and its successor. The resulting imagelist usually produces a much smaller file.

The `desconstruct` method starts by copying the first image in the list to the output imagelist. Then, for each pair of images, `deconstruct` computes the smallest rectangle that encompasses all the changes between the first and second image and stores just the changed rectangle of the second image, along with the offset of the rectangle relative to the boundary of the first image.

#### Returns

A new imagelist

#### Magick API

DeconstructImages

#### See also

optimize_layers

### dup

imagelist.dup -> anImageList

#### Description

Makes a shallow copy of the receiver. The image elements in the new imagelist are references to the image elements in the original imagelist, not copies.

#### See also

copy, clone

### display

imagelist.display [ { optional arguments } ] -> self

#### Description

Displays the images in the imagelist to any X Window screen. By default displays to the local screen. You can specify a different screen by assigning the name to the `server_name` attribute in the optional arguments block.

#### Returns

self

#### See also

animate, Image#display

#### Note

The display method is not supported on native MS Windows.

#### Magick API

DisplayImages

### flatten_images

imagelist.flatten_images -> anImage

#### Description

Combines all the images in the imagelist into a single image by overlaying each successive image onto the preceding images. If a image has transparent areas, the underlying image will show through. Use the page attribute to specify the position of each image with respect to the preceding images.

This is useful for combining Photoshop layers into a single image.

#### Returns

An image

#### Example

#### See also

coalesce

#### Magick API

FlattenImageList

### from_blob

imagelist.from_blob(blob[, blob...]) [ { optional arguments } ] -> self

#### Description

Creates images from the blob (Binary Large Objects) arguments and appends the images to the imagelist.

#### Arguments

A blob can be a string containing an image file such as a JPEG or GIF. The string can contain a multi-image file such as an animated GIF or a Photoshop image with multiple layers. A blob can also be one of the strings produced by to_blob. Control how the image(s) are created by setting additional Image::Info attributes in the optional block argument. Useful attributes include scene, number_scenes, and extract.

#### Returns

An image created from the blob argument(s). The `scene` attribute is set to the last image in the imagelist.

#### Example

    require 'RMagick'

    f = File.open('Cheetah.jpg')
    blob = f.read

    ilist = Magick::ImageList.new
    ilist.from_blob(blob)
    ilist.display

#### See also

to_blob, Image#to_blob, Image.from_blob

#### Magick API

BlobToImageList

### inspect

imagelist.inspect -> aString

#### Description

Produces a string that describes the images in the imagelist.

#### Arguments

#### Returns

The returned string is a concatenation of the strings returned by Image#inspect for all the images in the imagelist.

#### Example

    i = Magick::ImageList.new("images/Button_A.gif", "images/Button_B.gif")
    » [images/Button_A.gif GIF 127x120+0+0 PseudoClass 256c 8-bit 18136b
    images/Button_B.gif GIF 127x120+0+0 PseudoClass 256c 8-bit 5157b]
    scene=1

#### See also

Image#inspect

### map

imagelist.map(reference, dither) -> anImageList

#### Description

Reduces the colors in the imagelist images to the set of colors in the reference image.

#### Arguments

reference
  An image or a imagelist. If an imagelist, `map` uses the current image as the reference image.
dither
  if `true`, dither the mapped images.

#### Returns

A new imagelist the same length as the receiver.

#### Example

This example demonstrates how to map images into the 216 "Web safe" colors. Mouse over the image to see the images before mapping.

#### See also

Image#map, quantize

#### Magick API

MapImages

### montage

imagelist.montage [ { optional arguments } ] -> anImageList

#### Description

Creates a composite image by reducing the size of the input images and arranging them in a grid on the background color or texture of your choice. There are many configuration options. For example, you can specify the number of columns and rows, the distance between images, and include a label with each small image (called a tile).

All of `montage`'s configuration options are specified by assigning values to attributes in a block associated with the method call.

As you can see in the examples below, when you assign a value to a montage attribute you must specify `self` as the receiver so that Ruby can distinguish the method call from an assignment to a local variable.

You may assign a Pixel object to any attribute that accepts a color name.

#### Montage attributes

background_color=
  The composite image background color.
border_color=
  The tile border color.
border_width=
  The tile border width in pixels.
compose=
  The composite operator to use when compositing the tile images onto the background. The default composition operator is `OverCompositeOp`.
  Hint: You can use a different composite operator for each tile by setting each image's compose= attribute to the desired operator. In the optional arguments block, set `compose` to UndefinedCompositeOp.
fill=
  If the tiles have labels, the label fill color. The default fill color is black.
font=
  If the tiles have labels, the label font. The default font is Helvetica.
frame=
  The size of an ornamental frame surrounding each tile. The frame specification may be either a string or a Geometry object. If the argument is a string, it must have the form `<width>x<height>+<outer bevel width>+<inner bevel width>`. If the argument is a Geometry object, specify the width and height of the frame with the `width` and `height` attributes, and specify the outer bevel width and the inner bevel width with the `x` and `y` attributes. The values are in pixels. For example, to surround each tile with a frame 20 pixels wide by 20 pixels high and a 4-pixel inner and outer bevel, use:

      self.frame = "20x20+4+4"

  or

      self.frame = Magick::Geometry.new(20,20,4,4)

  If the tile has a label, the label is included in the frame. The default is to have no frame.
  See Image#frame.
geometry=
  The size of the tiles and the distance between tiles. The value can be either a geometry string or a Geometry object. The geometry string has the form: `<tile-width>x<tile-height>+<distance-between-columns>+<distance-between-rows>`. If you use a Geometry object, specify the tile width and height with the `width` and `height` attributes, and the distance between rows and distance between columns by the `x` and `y` attributes. To create tiles that are 130 pixels wide and 194 pixels tall, with 10 pixels between each column of tiles and 5 between each row, use:

      self.geometry = "130x194+10+5"

  or

      self.geometry = Magick::Geometry.new(130, 194, 10, 5)

  Both the geometry string and the `Geometry` object support flags that specify additional constraints. The default geometry is "120x120+4+3>".
gravity=
  The direction used when adding the tile labels. (See annotate.)
matte_color=
  The matte color. The default is #bdbdbd.
pointsize=
  If the tiles have labels, the size of the label font in points. The default is 12 points.
shadow=
  If set to `true`, adds a drop shadow to each tile. The default is `false`.
stroke=
  If the tiles have labels, sets the stroke (outline) color of the label text. The default is "transparent".
texture=
  A image to be tiled on the background of the composite image. If present, this attribute overrides the background color. For example, to use ×Magick's built-in "granite" texture as the background, use:

      self.texture = Magick::Image.read("granite:").first

  The default is no texture.

tile=
  The number of columns and rows to use when arranging the tiles on the composite image. The value can be either a string or a Geometry object. If the value is a string, it should have the form `"<columns>x<rows>"`. If the value is a Geometry object, specify the number of columns as the `width` attribute and the number of rows as the `height` attribute. `montage` always generates all the rows, leaving empty cells if necessary. To arrange the tiles 4 across and 10 down, use:

      self.tile = "4x10"

  or

      self.tile = Magick::Geometry.new(4,10)

  The default is "6x4". If there are too many tiles to fit on one composite image, `montage` creates multiple composite images.

title=
  Adds a title over the whole montage.

#### Tile labels

To add labels to the tiles, assign a "Label" property to each image. The `montage` method will use the value of the property as the label. For example,

    img[2]['Label'] = "Mom's Birthday"

See []=.

#### Returns

An imagelist that contains as many images as are required to display all the tiles.

#### Magick API

MontageImages

### morph

imagelist.morph(n) -> anImageList

#### Description

Transforms a image into another image by inserting `n` in-between images. Requires at least two images. If more images are present, the 2nd image is transformed into the 3rd, the 3rd to the 4th, etc.

#### Arguments

The number of in-between images to insert between each pair of images.

#### Returns

An imagelist containing copies of the original images plus the in-between images.

#### Example

This animated GIF was created by reading the "0", "1", "2" and "3" images, then using `morph` to create 8 images between each original image. Mouse over the image to start the animation.

#### Magick API

MorphImages

### mosaic

imagelist.mosaic -> anImage

#### Description

Composites all the images into a single new image. The location of each image is determined by the value of its page attribute.

#### Returns

An image

#### Example

#### See also

coalesce, flatten_images, montage

#### Magick API

MosaicImages

### new_image

imagelist.new_image(columns, rows[, fill]) [ { optional arguments } ] -> self

#### Description

Adds a new image to the imagelist. The image can have an optional fill applied to it.

#### Arguments

Creates a new image with the specified number of rows and columns. If the optional `fill` argument is used, calls the `fill` method to fill the image. Otherwise, the image is filled with the background color.

You can set any Image::Info attributes in an associated block. These attributes supply options to be used when creating the image. For example, you can specify the background color to fill the image with (see the example), the depth, border color, etc.

#### Returns

self

#### Example

Create a square red image.

    imagelist = Magick::ImageList.new
    imagelist.new_image(100, 100) { self.background_color = "red" }

### optimize_layers

imagelist.optimize_layers(layer_method) -> anImageList

#### Description

Optimizes or compares the images in the list. Equivalent to the `-layers` option in ImageMagick's `mogrify` command.

With the CompareAnyLayer, CompareClearLayer, and CompareOverlayLayer arguments, `optimize_layers` compares each image with the next in a sequence and returns the minimum bounding region of all the pixel differences (of the `LayerMethod` specified) it discovers.

The images in the list do NOT have to be the same size, though it is best that all the images are fully 'coalesced' (images are all the same size, on a flattened canvas, and represent how an specific frame should look is animatated)

If images are not the same size as the page canvas size of first image, then it is alpha composed using 'Copy' onto the previous frame compared. That is the differences only within the overlay area are looked at.

No dispose methods are applied, though this does not matter for animations which are a fully coalesced sequence of images.

With OptimizeLayer, `optimize_layers` compares each image the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace each frame, while preserving the results of the animation.

OptimizePlusLayer is the same as OptimizeLayers, but may also add or even remove extra frames in the animation, if it improves the total number of pixels in the resulting GIF animation.

With DisposeLayer, `optimize_layers` returns the coalesced frames of a GIF animation as it would appear after the GIF dispose method of that frame has been applied. That is it returns the appearance of each frame before the next is overlaid.

The `optimize_layers` method corresponds to the `-layers` option on ImageMagick's `convert` and `mogrify` commands. Anthony Thyssen's excellent Examples of ImageMagick Usage site has very detailed information and examples of the `-layers` option and and the optimization methods .

#### Arguments

One of the following `MagickLayerMethod` values:

- CoalesceLayer
- CompareAnyLayer
- CompareClearLayer
- CompareOverlayLayer
- DisposeLayer
- OptimizeLayer
- OptimizePlusLayer

#### Returns

A new imagelist

#### See also

deconstruct is an alias for `optimize_layers` with the `CompareAnyLayer` argument.

coalesce is an alias for `optimize_layers` with the `CoalesceLayer` argument.

#### Magick API

OptimizeImageLayers, CompareImageLayers (available in ImageMagick 6.2.6)

### ping

imagelist.ping(filename[, filename...]) -> self
imagelist.ping(file[, file...]) -> self

#### Description

Reads the image files and creates one or more images that contain all the image attributes but without the pixel data. If all you need is the image attributes, the `ping` method is much faster and consumes less memory than `read`.

#### Arguments

One or more image file names or open file objects.

#### Returns

self

#### Example

    imagelist = Magick::ImageList.new
    imagelist.ping "Button_A.gif"
    puts "The image has #{i.columns} columns and #{i.rows} rows." »
          The image has 127 columns and 120 rows.

#### See also

read

#### Magick API

PingImage

### quantize

imagelist.quantize(nc=256, colorspace=`Magick::RGBColorspace`, dither=`true`, tree_depth=0, measure_error=`false`) -> anImageList

#### Description

Analyzes the colors within a set of reference images and chooses a fixed number of colors to represent the set. The goal of the algorithm is to minimize the difference between the input and output images while minimizing the processing time.

#### Arguments

nc
  The maximum number of colors to use in the output images. Must be less than or equal to MaxRGB.
colorspace
  The colorspace to quantize in. Color reduction, by default, takes place in the RGB color space. Empirical evidence suggests that distances in color spaces such as YUV or YIQ correspond to perceptual color differences more closely than do distances in RGB space. The Transparent color space behaves uniquely in that it preserves the matte channel of the image if it exists.
dither
  Apply Floyd/Steinberg error diffusion to the image. When the size of the color palette is less than the image colors, this trades off spacial resolution for color resolution by dithering to achieve a similar looking image.
tree_depth
  Specify the tree depth to use while quantizing. The values 0 and 1 support automatic tree depth determination. The tree depth may be forced via values ranging from two to eight. The ideal tree depth depends on the characteristics of the input image, and may be determined through experimentation.
measure_error
  Calculate quantization errors when quantizing the image. Stores the results for each image in the imagelist mean_error_per_pixel, normalized_maximum_error, and normalized_mean_error attributes. Stores the number of colors used for the image in the total_colors attribute.

#### Returns

A new imagelist containing quantized copies of the images in the original image.

#### Example

This example shows the effect of quantizing 3 images to a set of 16 colors in the RGB colorspace. Mouse over the image to see the images before quantizing.

#### See also

Image#quantize

#### Magick API

QuantizeImages

### read

imagelist.read(filename[, filename...]) [ { optional arguments } ] -> self
imagelist.read(file[, file...]) [ { optional arguments } ] -> self

#### Description

Reads one or more image files and adds the images to the imagelist. After reading all the files, sets the scene number to the last image in the list.

The image files may be multi-frame (animated or layered) files. In this case `read` adds multiple images per file to the imagelist.

#### Arguments

One or more filenames or open file objects. You can also specify optional arguments to be used when reading the file(s) by setting Image::Info attributes in the optional block.

#### Returns

self

#### Example

    i = Magick::ImageList.new
    number = '0'
    4.times do
            i.read "images/Button_" + number + ".gif"
            number.succ!
            end

Also see the morph.rb example and the demo.rb example.

#### See also

Image.read

#### Magick API

ReadImage

#### Notes

You can create images using ×Magick's built-in formats with the `read` method. See Built-in image formats.

### to_blob

imagelist.to_blob [ { optional arguments } ] -> aString

#### Description

Converts the images in the imagelist to a blob. A blob contains data that directly represent a particular image format in memory instead of on disk.

Control the format of the blob by setting Image::Info attributes in an associated block.

#### Returns

The blob in the form of a string

#### Example

    i = Magick::ImageList.new "birthday.png"
    s = i.to_blob » a string representing the image.

#### See also

from_blob, Image#to_blob, Image.from_blob

#### Magick API

ImageListToBlob

### write

imagelist.write(filename) [ { optional arguments } ] -> self
imagelist.write(file) [ { optional arguments } ] -> self

#### Description

If the image format indicated by the filename supports multiple images per file (animated images), `write` writes all the images in the imagelist to a single file. Otherwise, `write` writes each image to a separate file.

Regardless of the original format, `write` converts the images to the format specified by the filename.

If the imagelist contains more than one image and the output format does not support multi-frame images, each image is written to a file that has the filename you specify followed by a period (.) and the scene number. You can change this behavior by embedding a %d, %0Nd, %o, %0No, %x, or %0Nx printf format specification in the file name.

#### Arguments

A filename or open file object. Indicate the desired image format either by the suffix (i.e. `.jpg`, `.png`) or the prefix (`ps:`) to the filename. If the argument is an open file object, you can specify a format for each image in the list by setting its format attribute.

You can also specify optional arguments by setting Image::Info attributes in an associated block.

#### Returns

self, or `nil` if the format cannot be determined.

#### Example

    # The PNG format does not support multi-frame files,
    # so each image is written to a separate file.
    i = Magick::ImageList.new "animated.gif"
    p i.length » 3 # contains 3 images
    i.write "test.png" » test.png.0
                       » test.png.1
                       » test.png.2
    # ×Magick's MIFF format does support multi-frame
    # files, so all 3 images are written to one file.
    i.write "animated.miff" » animated.miff

#### See also

Image#write

#### Magick API

WriteImages