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

Magick API

ProfileImage

Note

×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} ] -> image
image.properties -> 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
  • MultiplyQuantumOperator
  • OrQuantumOperator
  • RShiftQuantumOperator
  • SubtractQuantumOperator
  • XorQuantumOperator
rvalue
a Numeric operation rvalue.
channel
A ChannelType constant. 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

Magick API

RadialBlurImage

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

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

resize

image.resize(new_width, new_height, filter=LanczosFilter, blur=1.0) -> anImage
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.
blur
The blur factor. 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, blur=1.0) -> image
image.resize!(scale_factor) -> image

Description

In-place form of resize.

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) -> anImage

Description

Rotate the receiver by the specified angle. Positive angles rotate counter-clockwise (right-hand rule), while negative angles rotate clockwise. Rotated images are usually larger than the originals and have "empty" triangular corners. Empty triangles left over from shearing the image are filled with the color defined by the pixel at location (0,0).

Arguments

The number of degrees to rotate the image.

Returns

A new image

Example

rotate example

See also

affine_transform, shear

Magick API

RotateImage

rotate!

image.rotate!(amount) -> image

Description

In-place form of rotate.

Returns

self

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 constant. 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.

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

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

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 constant 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

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

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.

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

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