class Image < Object (class and instance methods, part 3)
mixes in Comparable

Table of Contents

instance methods

instance methods

preview

image.preview(aPreviewType) -> anImage

Description

Creates an image that contains 9 small versions of the receiver image. The center image is the unchanged receiver. The other 8 images are variations created by transforming the receiver according to the specified preview type with varying parameters.

A preview image is an easy way to "try out" a transformation method.

Arguments

One of the following PreviewType constants:

Returns

A new image

Example

This half-size preview demonstrates the SolarizePreview argument.

preview example

Magick API

PreviewImage

profile!

image.profile!(name, profile) -> image

Description

Adds or removes a ICM, IPTC, or generic profile from an image. If profile is nil, the specified profile is removed from the image. Use profile('*', nil) to remove all profiles from the image.

Arguments

name
The profile name, or "*" to represent all the profiles in the image.
profile
The profile value, or nil to cause the profile to be removed.

Returns

self

See also

add_profile and delete_profile perform very similar functions. However, add_profile accepts the name of a profile file on disk instead of the profile data itself and, if the file contains more than one profile, will load all the profiles at once.

Magick API

ProfileImage

Notes

×Magick does not automatically remove profiles when resizing images. If you are trying to make your JPEG thumbnail images as small as possible, use profile! to remove any profiles from the image as well. Also see strip!

properties

image.properties [ {|name,value| block} ] -> aHash

Description

If called with an associated block, properties runs the block once for each property defined for the image. The block arguments are the property name and its value. If there is no block, properties returns a hash with one element for each property. The hash key is the property name and the associated value is the property value.

Returns

If called without a block, returns a hash, otherwise returns self.

See also

[ ], [ ]=

Note

The EXIF property is not created until the first time an EXIF tag or entry number is referenced.

quantize

image.quantize(number_colors=256, colorspace=Magick::RGBColorspace, dither=true, tree_depth=0, measure_error=false) -> anImage

Description

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

Arguments

number_colors
The maximum number of colors in the result image. Must be <= 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
Set to true to 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
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 2 to 8. The ideal tree depth depends on the characteristics of the input image, and may be determined through experimentation.
measure_error
Set to true to calculate quantization errors when quantizing the image.

Returns

A new image

Example

See the example for colorize.

See also

ordered_dither, posterize, ImageList#quantize

Magick API

QuantizeImage

quantum_operator

image.quantum_operator(operator, rvalue, channel=AllChannels) -> anImage

Description

Performs the requested integer arithmetic operation on the selected channel of the image. This method allows simple arithmetic operations on the component values of all pixels in an image. Of course, you could also do this in Ruby using get_pixels and store_pixels, or view, but quantum_operator will be faster, especially for large numbers of pixels, since it does not need to convert the pixels from C to Ruby.

Arguments

operator
One of the following QuantumExpressionOperator constants:
  • AddQuantumOperator
  • AndQuantumOperator
  • DivideQuantumOperator
  • LShiftQuantumOperator
  • MaxQuantumOperator*
  • MinQuantumOperator*
  • MultiplyQuantumOperator
  • OrQuantumOperator
  • RShiftQuantumOperator
  • SubtractQuantumOperator
  • XorQuantumOperator
* Available in ImageMagick 6.2.0 and later.
rvalue
a Numeric operation rvalue.
channel
A ChannelType value. The default is to operate on all channels.

Returns

self

Example

Divide the red component of all the pixels in the image by 2:

img.quantum_operator(DivideQuantumOperator, 2, RedChannel)

See also

The Image:View class supports operations on individual pixels and collections of pixels, as well as operations on channels within pixels. See view, below.

Magick API

QuantumOperatorRegionImage (GraphicsMagick 1.1), EvaluateImageChannel (ImageMagick)

radial_blur

image.radial_blur(aFloat) -> anImage

Description

Applies a radial blur to the image.

Arguments

angle
Amount of blur, in degrees

Returns

A new image

Example

radial_blur example

See also

blur_image, gaussian_blur, motion_blur, radial_blur_channel

Magick API

RadialBlurImage

radial_blur_channel

image.radial_blur_channel(aFloat [, channel...]) -> anImage

Description

Applies a radial blur to the selected image channels.

Arguments

angle
Amount of blur, in degrees
channel...
0 or more ChannelType arguments. If no channels are specified, all the channels are blurred.

Returns

A new image

See also

radial_blur

Magick API

RadialBlurImageChannel (available in ImageMagick 6.2.4)

raise

image.raise(width=6, height=6, raised=true) -> anImage

Description

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image.

Arguments

width
The width of the raised edge in pixels. The default is 6.
height
The height of the raised edge in pixels. The default is 6.
raised
If true, the image is raised, otherwise lowered.

Returns

A new image

Example

raise example

Magick API

RaiseImage

random_threshold_channel

image.random_threshold_channel( thresholds, [channel...] ) -> anImage

Description

Changes the value of individual pixels based on the intensity of each pixel compared to a random threshold. The result is a low-contrast, two color image.

Arguments

thresholds
A geometry string containing LOWxHIGH thresholds. The string is in the form `XxY'. The Y value may be omitted, in which case it is assigned the value MaxRGB-X. If an % appears in the string then the values are assumed to be percentages of MaxRGB. If the string contains 2x2, 3x3, or 4x4, then an ordered dither of order 2, 3, or 4 will be performed instead. A Geometry object may be used as well.
channel...
0 or more ChannelType arguments. If no channels are specified, all the channels are thresholded.

Returns

A new image

Example

geom = Geometry.new(MaxRGB/2)
random_threshold_channel(geom, RedChannel)

random_threshold_channel example

See also

adaptive_threshold, bilevel_channel, threshold

Magick API

RandomThresholdImageChannel

recolor

image.recolor(color_matrix) -> anImage

Description

Use this method to translate, scale, shear, or rotate image colors. Although you can use variable sized matrices, typically you use a 5×5 for an RGBA image and a 6×6 for CMYKA. Populate the last row with normalized values to translate.

Arguments

An array of Float values representing the recolor matrix.

Magick API

RecolorImage (introduced in ImageMagick 6.3.1)

reduce_noise

image.reduce_noise(radius) -> anImage

Description

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value.

Arguments

radius
A neighbor is defined by radius. Use a radius of 0 and reduce_noise selects a suitable radius for you.

Returns

A new image

Example

The left side of the image has been modified by add_noise. The right side has been filtered by reduce_noise(0).

reduce_noise example

See also

enhance, unsharp_mask

Magick API

ReduceNoiseImage

resample

image.resample(horizontal_res=72.0[, vertical_res]) -> anImage

Description

Resample image to specified horizontal and vertical resolution.

Resize the image so that its rendered size remains the same as the original at the specified target resolution. For example, if a 300 DPI image renders at 3 inches by 2 inches on a 300 DPI device, when the image has been resampled to 72 DPI, it will render at 3 inches by 2 inches on a 72 DPI device. Note that only a small number of image formats (e.g. JPEG, PNG, and TIFF) are capable of storing the image resolution. For formats which do not support an image resolution, the original resolution of the image must be specified via the density attribute prior to specifying the resample resolution.

Arguments

horizontal_res
the target horizontal resolution. The default is 72.0.
vertical_res
the target vertical resolution. The default is horizontal_res.

resize

image.resize(new_width, new_height, filter=LanczosFilter, support=1.0) -> image
image.resize(scale_factor) -> anImage

Description

Changes the size of the receiver to the specified dimensions.

Arguments

You can specify the new size in two ways. Either specify the new width and height explicitly, or specify a scale factor, a number that represents the percentage change.

Use the change_geometry method to resize an image with constraints such as "maintain the current proportions."

new_width, new_height
The desired width and height.
filter
The filter to use when resizing. If you do not specify a filter argument, resize uses the value of the receiver's filter attribute. Most of the filters are FIR (finite impulse response), however, Bessel, Gaussian, and Sinc are IIR (infinite impulse response). Bessel and Sinc are windowed (brought down to zero) with the Blackman filter.
support
Values > 1 increase the blurriness. Values < 1 increase the sharpness. If this argument is not specified, resize uses the value of the receiver's blur attribute.
scale_factor
You can use this argument instead of specifying the desired width and height. The percentage size change. For example, 1.25 makes the new image 125% of the size of the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.

Returns

A new image

See also

change_geometry, resize!, magnify, minify, sample, scale, thumbnail

Magick API

ResizeImage

resize!

image.resize!(new_width, new_height, filter=LanczosFilter, support=1.0) -> image
image.resize!(scale_factor) -> image

Description

In-place form of resize.

Returns

self

resize_to_fit

image.resize_to_fit(new_width, new_height) -> anImage

Description

A convenience method. Resize the image to fit within the specified dimensions while retaining the original aspect ratio.

Arguments

new_width, new_height
The maximum width and height of the resized image. In order to retain the aspect ratio of the input image, the actual dimensions of the resized image may be different but will not be larger than the specified values.

Returns

A new image

See also

change_geometry, resize

resize_to_fit!

image.resize_to_fit!(new_width, new_height) -> image

Description

In-place form of resize_to_fit.

Returns

self

roll

image.roll(x_offset, y_offset) -> anImage

Description

Offsets an image as defined by x_offset and y_offset.

Arguments

x_offset
The number of columns to offset the image.
y_offset
The number of rows to offset the image.

Returns

A new image

Example

This image has been offset 25% in both directions.

roll example

Magick API

RollImage

rotate

image.rotate(amount [, qualifier]) -> anImage

Description

Rotate the receiver by the specified angle. Positive angles rotate clockwise while negative angles rotate counter-clockwise. New pixels introduced by the rotation are the same color as the current background color. Set the background color to "none" to make the new pixels transparent black.

Arguments

amount
The number of degrees to rotate the image.
qualifier
If present, either ">" or "<". If ">", rotates the image only if the image's width exceeds its height. If "<" rotates the image only if its height exceeds its width. If this argument is omitted the image is always rotated.

Returns

A new image, or nil if the image was not rotated because it did not meet the qualification specified by the second argument.

Example

rotate example

See also

affine_transform, shear

Magick API

RotateImage

rotate!

image.rotate!(amount [, qualifier]) -> image

Description

In-place form of rotate.

Returns

self, or nil if the image was not rotated because it did not meet the qualification specified by the second argument.

sample

image.sample(new_width, new_height) -> anImage
image.sample(scale_factor) -> anImage

Description

Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.

Arguments

new_width, new_height
The desired width and height.
scale_factor
You can use this argument instead of specifying the desired width and height. The percentage size change. For example, 1.25 makes the new image 125% of the size of the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.

Returns

A new image

See also

sample!, magnify, minify, resize, scale, thumbnail

Magick API

SampleImage

sample!

image.sample!(new_width, new_height) -> image
image.sample!(scale_factor) -> image

Description

In-place form of sample.

Returns

self

scale

image.scale(new_width, new_height) -> anImage
image.scale(scale_factor) -> anImage

Description

Changes the size of an image to the given dimensions.

Arguments

new_width, new_height
The desired width and height.
scale_factor
You can use this argument instead of specifying the desired width and height. The percentage size change. For example, 1.25 makes the new image 125% of the size of the receiver. The scale factor 0.5 makes the new image 50% of the size of the receiver.

Returns

A new image

See also

scale!, magnify, minify, resize, sample, thumbnail

Magick API

ScaleImage

scale!

image.scale!(new_width, new_height) -> image
image.scale!(scale_factor) -> image

Description

In-place form of scale.

Returns

self

segment

image.segment(colorspace=RGBColorspace, cluster_threshold=1.0, smoothing_threshold=1.5, verbose=false) -> anImage

Description

Segments an image by analyzing the histograms of the color components and identifying units that are homogeneous with the fuzzy c-means technique.

Arguments

colorspace
A ColorspaceType value. Empirical evidence suggests that distances in YUV or YIQ correspond to perceptual color differences more closely than do distances in RGB space. The image is then returned to RGB colorspace after color reduction.
cluster_threshold
The number of pixels in each cluster must exceed the the cluster threshold to be considered valid.
smoothing_threshold
The smoothing threshold eliminates noise in the second derivative of the histogram. As the value is increased, you can expect a smoother second derivative.
verbose
If true, segment prints detailed information about the identified classes.

Returns

A new image

Example

segment(Magick::YUVColorspace, 0.4, 0.4)

segment example

Magick API

SegmentImage

sepiatone

image.sepiatone(threshold=MaxRGB) -> anImage

Description

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by sepia toning.

Arguments

threshold
Threshold ranges from 0 to MaxRGB and is a measure of the extent of the sepia toning. A threshold of 80% is a good starting point for a reasonable tone. The default is MaxRGB.

Returns

self

Example

sepiatone example

See also

You can get more control by using colorize.

Magick API

SepiaToneImage (available in ImageMagick 6.2.1)

set_channel_depth

image.set_channel_depth(channel, depth) -> self

Description

Sets the depth of the image channel.

Arguments

channel
A ChannelType value
depth
The desired depth (must be no greater than QuantumDepth)

Returns

self

See also

channel_depth

Magick API

SetImageChannelDepth

shade

image.shade(shading=false, azimuth=30, elevation=30) -> anImage

Description

Shines a distant light on an image to create a three-dimensional effect. You control the positioning of the light with azimuth and elevation; azimuth is measured in degrees off the x axis and elevation is measured in pixels above the Z axis.

Arguments

shading
If true, shade shades the intensity of each pixel.
azimuth, elevation
The light source direction. The azimuth is measured in degrees. 0° is at 9 o'clock. Increasing values move the light source counter-clockwise.

Returns

A new image

Example

shade(true, 50, 50)

shade example

Magick API

ShadeImage

shadow

image.shadow(x_offset=4, y_offset=4, sigma=4.0, opacity=1.0) -> anImage

Description

Draws the shadow of opaque parts of the image. This method only works when the image has opaque parts and transparent parts. Note that the resulting image is just the shadow. You must composite the original image over the shadow to produce the shadowed results.

Arguments

x_offset
The shadow x-offset
y_offset
The shadow y-offset
sigma
The standard deviation of the Gaussian operator used to produce the shadow. The higher the number, the "blurrier" the shadow, but the longer it takes to produce the shadow. Must be > 0.0.
opacity
The percent opacity of the shadow. May be either a number between 0.1 and 1.0, or a string in the form "NN%" between "1%" and "100%". If the percentage is greater than 100 it is reduced to 100.

Returns

A new image

Example

shadow example

Magick API

ShadowImage (available in ImageMagick 6.1.7)

Notes

The shadow image is 2×sigma pixels larger on a side than the original image, as can be seen in the example above.

sharpen

image.sharpen(radius=0.0, sigma=1.0) -> anImage

Description

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and sharpen selects a suitable radius for you.

Arguments

The radius and standard deviation of the Gaussian operator.

Returns

A new image

Magick API

SharpenImage

See also

virtual_pixel_method

sharpen_channel

image.sharpen_channel( radius, sigma [,channel...] ) -> anImage

Description

Sharpens one or more image channels. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma) . For reasonable results, radius should be larger than sigma. Use a radius of 0 and sharpen_channel selects a suitable radius for you.

Arguments

radius, sigma
The radius and standard deviation of the Gaussian operator.
channel...
0 or more ChannelType arguments. If no channels are specified, all the channels are sharpened.

Returns

A new image

See also

sharpen

Magick API

SharpenImageChannel (available in ImageMagick 6.0.1)

shave

image.shave(width, height) -> anImage

Description

Removes pixels from the edges of the image, leaving the center rectangle.

Arguments

width
The number of pixels to remove from each side of the receiver, not to exceed half the original width.
height
The number of pixels to remove from the top and bottom of the receiver, not to exceed half the original height.

Returns

A new image

Example

shave example

See also

shave!, crop

Magick API

ShaveImage

shave!

image.shave!(width, height) -> image

Description

In-place form of shave.

Returns

self

shear

image.shear(x_shear, y_shear) -> anImage

Description

Shearing slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

Arguments

The X and Y shear angles, measured in degrees. These values must not be 180.0. If either value is 0, no shearing will occur.

Returns

A new image

Example

shear example

See also

affine_transform, rotate

Magick API

ShearImage

sigmoidal_contrast_channel


image.sigmoidal_contrast_channel(contrast=3.0, midpoint=50.0, sharpen=false[,channel...]) -> anImage

Description

Adjusts the contrast of an image channel with a non-linear sigmoidal contrast algorithm. Increases the contrast of the image using a sigmoidal transfer function without saturating highlights or shadows.

Arguments

contrast
indicates how much to increase the contrast (0 is none; 3 is typical; 20 is pushing it)
midpoint
indicates where midtones fall in the resultant image (0 is white; 50% is middle-gray; 100% is black)
sharpen
Set sharpen to true to increase the image contrast otherwise the contrast is reduced.
channel...
0 or more ChannelType arguments. If no channels are specified, all the channels are adjusted.

Returns

A new image

See also

contrast

Magick API

SigmoidalContrastImageChannel (available in ImageMagick 6.2.1)

signature

image.signature -> aString

Description

Computes a message digest from an image pixel stream with an implementation of the NIST SHA-256 Message Digest algorithm. This signature uniquely identifies the image and is convenient for determining if an image has been modified or whether two images are identical.

×Magick adds the computed signature to the image's properties.

Returns

The signature as a 64-character string.

Example

img = Image.read('ex/images/Flower_Hat.jpg').first »
  ex/images/Flower_Hat.jpg JPEG 200x250 DirectClass 8-bit 9761b
img.properties »
  {"comment"=>"File written by Adobe Photoshop\250 4.0"}
img.signature »
  "485e01ecba1a1f47924d67b887cb07b474f695841733796dfa3c2876965c7e8b"
img.properties »
  {"signature"=>"485e01ecba1a1f47924d67b887cb07b474f695841733796dfa3c2876965c7e8b",
   "comment"=>"File written by Adobe Photoshop\250 4.0"}

See also

<=>, difference

Magick API

SignatureImage

sketch

image.sketch(radius=0.0, sigma=1.0, angle=0.0) -> anImage

Description

Simulates a pencil sketch. For best results start with a grayscale image.

Arguments

radius, sigma
The radius and sigma of the Gaussian operator
angle
The angle toward which the image is sketched.

Returns

A new image

Example

sketch example

Magick API

SketchImage (available in ImageMagick 6.2.8)

solarize

image.solarize(threshold=50) -> anImage

Description

Applies a special effect to the image similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light.

Arguments

Ranges from 0 to MaxRGB and is a measure of the extent of the solarization. The default is 50.

Returns

A new image

Example

solarize example

Magick API

SolarizeImage

splice

image.splice(x, y, width, height[, color]) -> anImage

Description

Splice a solid color into the image as defined by the x, y, width, and height arguments. This method is the opposite of chop.

Arguments

x, y, width, height
Describe the rectangle to be spliced.
color
The color to be spliced. Either a color name or a pixel. If omitted, uses the image's background color.

Returns

A new image

Example

splice example

See also

color_fill_to_border, color_floodfill, color_reset!, erase!, opaque

Magick API

SpliceImage

spread

image.spread(radius=3) -> anImage

Description

Randomly displaces each pixel in a block defined by the radius parameter.

Returns

A new image

Example

spread example

Magick API

SpreadImage

statistics

image.statistics -> see below

Description

Computes the minimum, maximum, mean, standard deviation, and variance for each channel in the image.

Returns

The statistics method returns a Statistics class object. This class defines four channel attributes: red, green, blue, and opacity. Each channel attribute is a Statistics::Channel class object. This class defines 5 statistic attributes: min, max, mean stddev, and var. See the example below.

Example

require 'pp'

img = Image.read("Flower_Hat.jpg").first
stats = img.statistics

pp stats »
    #<Magick::Statistics
    red=
      #<Magick::Statistics::Channel
      max=1.0,
      min=0.0,
      mean=0.627182352941187,
      stddev=0.231399683489667,
      var=0.0535458135191179>,
    green=
      #<Magick::Statistics::Channel
      max=1.0,
      min=0.0,
      mean=0.571999607843132,
      stddev=0.22246563644744,
      var=0.0494909593999647>,
    blue=
      #<Magick::Statistics::Channel
      max=1.0,
      min=0.0,
      mean=0.508869725490209,
      stddev=0.269422111063184,
      var=0.0725882739297426>,
    opacity=
      #<Magick::Statistics::Channel
      max=0.0,
      min=0.0,
      mean=0.0,
      stddev=0.0,
      var=0.0>>

p stats.red.stddev » 0.231399683489667

See also

channel_extrema, channel_mean

Magick API

GetImageStatistics (available in GraphicsMagick 1.1)

stegano

image.stegano(watermark, offset) -> anImage

Description

Hides a digital watermark in the receiver. You can retrieve the watermark by reading the file with the stegano: prefix, thereby proving the authenticity of the file.

The watermarked image must be saved in a lossless RGB format such as MIFF, or PNG. You cannot save a watermarked image in a lossy format such as JPEG or a pseudocolor format such as GIF. Once written, the file must not be modified or processed in any way.

Arguments

watermark
An image or imagelist to be used as the watermark. The watermark must be grayscale and should be substantially smaller than the receiver. The recovery time is proportional to the size of the watermark.
offset
The starting position within the receiver at which the watermark will be hidden. When you retrieve the watermark from the file, you must supply this value, along with the width and height of the watermark, in the size optional parameter to the read method.

Returns

A copy of the image containing the embedded watermark.

Example

stegano example

Magick API

SteganoImage

See also

watermark

stereo

image.stereo(offset_image) -> anImage

Description

Combines two images and produces a single image that is the composite of a left and right image of a stereo pair. Special red-green stereo glasses are required to view this effect.

Arguments

Another image or imagelist. If the argument is an imagelist, uses the current image.

Returns

A new image

Magick API

StereoImage

store_pixels

image.store_pixels(x, y, columns, rows, pixels) -> image

Description

Replace the pixels in the specified rectangle with the pixels in the pixels array.

Arguments

x, y
The x- and y-offset of the rectangle to be replaced.
columns, rows
The number of rows and columns in the rectangle.
pixels
An array of pixels. The number of pixels in the array must be the same as the number of pixels in the rectangle, that is, rows*columns.

Returns

The image, with the rectangle suitably altered.

Example

smile example

Also see the example for get_pixels.

See also

constitute, get_pixels, view

Magick API

SetImagePixels, SyncImagePixels

strip!

image.strip! -> image

Description

Strips an image of all profiles and comments.

Returns

self

Magick API

StripImage (available in ImageMagick and GraphicsMagick 1.1)

swirl

image.swirl(degrees) -> anImage

Description

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

Arguments

The number of degrees to swirl the image.

Returns

A new image

Example

This example is an animated image. Mouse over the image to start the animation.

swirl example

Magick API

SwirlImage

texture_fill_to_border

image.texture_fill_to_border(x, y, texture) -> anImage

Description

Replaces the target pixel at x, y and its neighbors that are not the border color with copies of the texture image. Use the fuzz attribute to specify how closely a pixel must match the border color.

Arguments

x, y
The x- and y-offset of the target pixel.
texture
An image or imagelist. If an imagelist, uses the current image.

Returns

A new image

Example

In this example the target is the pixel in the center of the image. The texture - in this case a picture of a girl in a flowered hat - replaces this pixel and its neighbors until reaching a black pixel. Mouse over the image to see the original image. Notice the plum-colored circles are replaced as well. Compare this result with the result of texture_floodfill, below.

texture_fill_to_border example

See also

color_fill_to_border, matte_fill_to_border

Magick API

ColorFloodfillImage

texture_floodfill

image.texture_floodfill(x, y, texture) -> anImage

Description

Replaces the target pixel at x, y and its neighbors that are the same color with the texture image. By default, the neighbor pixels must be exactly the same color as the target pixel. Use the fuzz attribute to specify how much difference is acceptable.

Arguments

x, y
The x- and y-offset of the target pixel.
texture
An image or imagelist. If an imagelist, uses the current image.

Returns

A new image

Example

In this example the target is the pixel in the center of the image. The texture - in this case a picture of a girl in a flowered hat - replaces this pixel and its same-colored neighbors. Mouse over the image to see the original image. Notice the plum-colored circles are not replaced. Compare this result with the result of texture_fill_to_border, above.

texture_floodfill example

See also

color_floodfill, matte_floodfill

Magick API

ColorFloodfillImage

threshold

image.threshold(threshold) -> anImage

Description

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.

Arguments

A value between 0 and MaxRGB.

Returns

A new image

Example

threshold(Magick::MaxRGB*0.55)

threshold example

See also

adaptive_threshold, bilevel_channel, random_threshold_channel

Magick API

ThresholdImage

thumbnail

image.thumbnail(new_width, new_height) -> anImage
image.thumbnail(scale_factor) -> anImage

Description

The thumbnail method is a fast resizing method suitable for use when the size of the resulting image is < 10% of the original.

Arguments

You can call thumbnail with either the new width and height or the scale factor.

new_width, new_height
The desired width and height in pixels.
scale_factor
The desired size represented as a floating-point number. For example, to make a thumbnail that is 9.5% of the size of the original image, use 0.095.

Returns

A new image

Example

img = Magick::Image.read("images/Cheetah.jpg").first
thumbnail = img.thumbnail(img.columns*0.09, img.rows*0.09)

See also

minify, resize, sample, scale

Magick API

ThumbnailImage

thumbnail!

image.thumbnail!(new_width, new_height) -> image
image.thumbnail!(scale_factor) -> image

Description

In-place form of thumbnail.

Returns

self

to_blob

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

Description

Creates a Binary Large OBject, a direct-to-memory version of the image. The from_blob method constructs an image from a BLOB created by this method.

Arguments

No required arguments, however you can specify the image format (such as JPEG, PNG, etc.) and depth by calling the format and depth attributes, as well as other Image::Info attributes as appropriate, in a block associated with the method.

Returns

A string containing the image data represented as a BLOB.

Example

to_blob example

See also

from_blob

Magick API

ImageToBlob

to_color

image.to_color(aPixel) -> aString

Description

Returns the color name for a pixel. Unlike the Pixel#to_color method, to_color uses the depth and matte attributes of the image to determine the color name.

Arguments

A Pixel object.

Returns

A color name.

Example

img = Image.read('ex/images/Flower_Hat.jpg').first
» ex/images/Flower_Hat.jpg JPEG 200x250 DirectClass 8-bit 9761b
pixel = img.pixel_color(img.columns/2, img.rows/2)
» #<struct Magick::Pixel red=216, green=147, blue=106, opacity=0>
img.to_color(pixel)
» "#D8936A"

See also

Pixel#to_color

Magick API

QueryColorname

transparent

image.transparent(color, opacity=Magick::TransparentOpacity) -> anImage

Description

Changes the opacity value of all the pixels that match color to the value specified by opacity. By default the pixel must match exactly, but you can specify a tolerence level by setting the fuzz attribute on the image.

Arguments

color
Either a color name or a pixel.
opacity
The new opacity value, either an opacity value or a number between 0 and MaxRGB. The default is TransparentOpacity.

Returns

A new image

Example

Mouse over the image to see the original. In this example, all the black pixels are made transparent. The resulting image has been composited over a plasma background, which shows through the transparent pixels.

transparent example

See also

matte_replace, Draw#matte

Magick API

TransparentImage

transpose

image.transpose -> anImage

Description

Creates a horizontal mirror image by reflecting the pixels around the central y-axis while rotating them by 90 degrees.

Returns

A new image

Example

transpose example

See also

flip, flop, rotate, transpose!, transverse

Magick API

TransposeImage (available in ImageMagick 6.2.8)

transpose!

image.transpose! -> self

Description

In-place form of transpose.

Returns

self

transverse

image.transverse -> anImage

Description

Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating them by 270 degrees

Returns

A new image

Example

transverse example

See also

flip, flop, rotate, transpose, transverse!

Magick API

TransposeImage (available in ImageMagick 6.2.8)

transverse!

image.transverse! -> self

Description

In-place form of transverse.

Returns

self

trim

image.trim -> anImage

Description

Removes the edges that are exactly the same color as the corner pixels. Use the fuzz attribute to make trim remove edges that are nearly the same color as the corner pixels.

Returns

A new image

Example

trim example

Magick API

CropImage

trim!

image.trim! -> self

In-place form of trim.

Returns

self

unique_colors

image.unique_colors -> anImage

Description

Constructs a new image with one pixel for each unique color in the image. The new image has 1 row. The row has 1 column for each unique pixel in the image.

Returns

A new image

Magick API

UniqueImageColors (available in ImageMagick 6.2.9)

unsharp_mask

image.unsharp_mask(radius=0.0, sigma=1.0, amount=1.0, threshold=0.05) -> anImage

Description

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and unsharp_mask selects a suitable radius for you.

Arguments

All arguments are optional.

radius
The radius of the Gaussian operator. The default is 0.0.
sigma
The standard deviation of the Gaussian operator. A good starting value is 1.0, which is the default.
amount
The percentage of the blurred image to be added to the receiver, specified as a fraction between 0 and 1.0. A good starting value is 1.0, which is the default.
threshold
The threshold needed to apply the amount, specified as a fraction between 0 and 1.0. A good starting value is 0.05, which is the default.

Returns

A new image

Example

unsharp_mask example

See also

enhance, median_filter, reduce_noise, unsharp_mask_channel

Magick API

UnsharpMaskImage

unsharp_mask_channel

image.unsharp_mask_channel(radius=0.0, sigma=1.0, amount=1.0, threshold=0.05 [,channel...]) -> anImage

Description

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and unsharp_mask_channel selects a suitable radius for you.

Only the specified channels are sharpened.

Arguments

All arguments are optional.

radius
The radius of the Gaussian operator. The default is 0.0.
sigma
The standard deviation of the Gaussian operator. A good starting value is 1.0, which is the default.
amount
The percentage of the blurred image to be added to the receiver, specified as a fraction between 0 and 1.0. A good starting value is 1.0, which is the default.
threshold
The threshold needed to apply the amount, specified as a fraction between 0 and 1.0. A good starting value is 0.05, which is the default.
channel...
0 or more ChannelType arguments. If no channels are specified, all the channels are sharpened. This is the equivalent of unsharp_mask.

Returns

A new image

See also

enhance, median_filter, reduce_noise, unsharp_mask

Magick API

UnsharpMaskImageChannel (available in ImageMagick 6.1.0)

view

image.view(x, y, width, height) -> aView
image.view(x, y, width, height) { |view| block } -> nil

Description

View is a convenience method that supports getting and setting individual image pixels by [i][j] coordinates. With no associated block, view returns an Image::View object. If the optional code block is given, it will be passed the Image::View object as an argument. The sync method will be called automatically when the block terminates. In this case, view returns nil.

Arguments

x, y
The offset of the view from the top-left corner of the image. Within the view, pixels are relative to the top-left corner of the view, not the image.
width, height
The width and height of the view. The view may not extend past the boundaries of image.

Returns

If the optional code block is present, view returns nil. If it is not present, view returns an Image::View object.

See

Image::View

Examples

The example image below has been scaled 500% for clarity.

view example

img = Image.new(40, 40) {self.background_color = 'lightcyan2'}

# The view is 400 pixels square, starting at
# column 10, row 5 from the top of the image.
img.view( 10, 5, 20, 20) do |view|

    # Set all the pixels in the view to green.
    view[][] = Pixel.new(0, MaxRGB)

    # Change the top and bottom rows to red.
    view[0][] = 'red'
    view[-1,1][] = 'red'

    # Set 6 pixels to black.
    view[[13,15]][[12,14,16]] = 'black'

    # Set 1 pixel to yellow.
    view[5][7] = 'yellow'

    # Change the green channel of all the
    # pixels on row 8.
    view[8][].green = MaxRGB/2

    # Change the blue channel of 8 pixels
    # on column 10.
    view[4,8][10].blue = MaxRGB
end

See also

pixel_color, get_pixels, store_pixels

Notes

The view method introduces a relatively high level of overhead to pixel manipulation compared to methods that use the ×Magick API to identify and change pixels. I recommend that you use view only when the number of pixels identified in the view is fairly small (a few thousand to a few hundred thousand, depending on your patience and the speed of your computer) and you need this degree of control.

vignette

image.vignette(x, y, radius=0.0, sigma=10.0) -> anImage

Description

Gradually shades the edges of the image by transforming the pixels into the background color.

Arguments

x
Influences the amount of background color in the horizontal dimension. Larger values of x make the vignette narrower. This argument should be positive and less than image.columns / 2. This argument is optional. If omitted, the default value is 0.10 * image.columns.
y
Influences the amount of background color in the vertical dimension. Larger values of y make the vignette shorter. This argument should be positive and less than image.rows / 2. This argument is optional. If omitted, the default value is 0.10 * image.rows.
radius, sigma
Controls the amount of blurring. Larger values of sigma increase the blurring at the expense of increased execution time. In general, radius should be larger than sigma, although if radius is 0 then ×Magick will choose a suitable value. Sigma must be non-zero. Choose a very small value for sigma to produce a "hard" edge.

Returns

A new image

Example

vignette example

Magick API

VignetteImage (available in ImageMagick 6.2.6)

Notes

The image produced by vignette is very similar to the image produced by RMagick's vignette.rb example script. However, the example script gives you more control over the size, shape, and background color of the vignette.

watermark

image.watermark(mark, lightness=1.0, saturation=1.0, x_offset=0, y_offset=0) -> anImage
image.watermark(mark, lightness=1.0, saturation=1.0, gravity, x_offset=0, y_offset=0) -> anImage

Description

Composites a watermark image on the target image using the Modulate composite operator. This composite operation operates in the HSL colorspace and combines part of the lightness, part of the saturation, and all of the hue of each pixel in the watermark with the corresponding pixel in the target image

Arguments

mark
The watermark image. Either an imagelist or an image. If an imagelist, uses the current image.
lightness
The fraction of the lightness component of the watermark pixels to be composited onto the target image. Must be a non-negative number or a string in the form "NN%". If lightness is a number it is interpreted as a percentage. Both 0.25 and "25%" mean 25%. The default is 100%.
saturation
The fraction of the saturation component of the watermark pixels to be composited onto the target image. Must be a non-negative number or a string in the form "NN%". If lightness is a number it is interpreted as a percentage. Both 0.25 and "25%" mean 25%. The default is 100%.
x_offset
The offset of the watermark, measured from the left-hand side of the target image. The default is 0.
y_offset
The offset of the watermark, measured from the top of the target image. The default is 0.

Watermark can be called with a gravity argument or without. When a gravity argument is specified but the x- and y-offsets are omitted, the watermark is positioned based on the value of the gravity argument:

NorthWestGravity
The watermark abuts the top and left sides of the image.
NorthGravity
The watermark is centered left-to-right and abuts the top of the image.
NorthEastGravity
The watermark abuts the top and right sides of the image.
EastGravity
The watermark is centered top-to-bottom and abuts the right side of the image.
SouthEastGravity
The watermark abuts the bottom and right sides of the image.
SouthGravity
The watermark is centered left-to-right and abuts the bottom of the image.
SouthWestGravity
The watermark abuts the bottom and left sides of the image.
WestGravity
The watermark is centered top-to-bottom and abuts the left side of the image.
CenterGravity
The watermark is centered left-to-right and top-to-bottom.

When the gravity argument is present and the x-offset (and optionally the y-offset) is present, the x- and y-offset are measured from the right and/or bottom edges of the target image based on the value of gravity. If the argument is NorthEastGravity, EastGravity, or SouthEastGravity, the x-offset is measured from the right side of the image. If the argument is SouthEastGravity, SouthGravity, or SouthWestGravity, the y-offset is measured from the bottom of the image. All other values are ignored and the x- and y-offset are measured from the upper-left corner of the image.

Returns

A new image

Example

See "Watermarking with Images" in Anthony Thyssen's Examples of ImageMagick Usage.

watermark example

See also

composite, stegano

wave

image.wave(amplitude=25.0, wavelength=150.0) -> anImage

Description

Creates a "ripple" effect in the image by shifting the pixels vertically along a sine wave whose amplitude and wavelength is specified by the given parameters.

Returns

A new image

Example

wave example

Magick API

WaveImage

See also

virtual_pixel_method

wet_floor

image.wet_floor(intial=0.5, rate=1.0) -> anImage

Description

Creates a "wet floor" reflection. The reflection is an inverted copy of the image that changes from partially transparent to entirely transparent. By default only the bottom third of the image appears in the reflection.

Note that the output image is just the reflection. This makes it easy to apply further transformations to the reflection before combining it with the original image.

Arguments

initial
A value between 0.0 and 1.0 that specifies the initial percentage of transparency. Higher values cause the top of the reflection to be more transparent, lower values less transparent. The default is 0.5, which means that the top of the reflection is 50% transparent.
rate
A non-negative value that specifies how rapidly the reflection transitions from the initial level of transparency to entirely transparent. The default value is 1.0, which means that the transition occurs in 1/3 the image height. Values greater than 1.0 speed up the transition (the reflection will have fewer rows), values lower than 1.0 slow down the transition (the reflection will have more rows). A value of 0.0 means that the level of transparency will not change.

Returns

A new image

Example

Here are four examples of wet_floor. The top image shows the result of appending the default reflection to the original image. The second image shows the result of decreasing the initial transparency to 0.25 and using 0.5 as the rate argument. The third image uses the same reflection as the second image but has a slant added. The bottom image is the same as the third image but with a ripple effect.

wet floor example

white_threshold

image.white_threshold(red_channel [, green_channel[, blue_channel[, opacity_channel]]]) -> anImage

Description

Forces all pixels above the threshold into white while leaving all pixels below the threshold unchanged.

Arguments

Each channel argument is a number between 0 and MaxRGB. All arguments except the first may be omitted. If the green_channel or blue_channel argument is omitted, the default value is the red_channel value. If the opacity_channel argument is omitted, the default value is OpaqueOpacity.

Returns

A new image

See also

black_threshold, bilevel_channel

Magick API

WhiteThresholdImage

write

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

Description

Writes the image to the specified file. ×Magick determines image format from the prefix or extension.

If the argument is an open file, ×Magick will write the image in its current format. You can force a different format by setting the image's format attribute.

Arguments

A file name or open file object. You may also specify optional arguments by setting Image::Info attributes in an associated block.

Returns

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

Example

Almost all of the examples call write.

See also

ImageList#write

Magick API

WriteImage