Magick::Image Class

Contents

Introduction

Image is the primary object in Magick++ and represents a single image frame (see image design). The STL interface must be used to operate on image sequences or images (e.g. of format GIF, TIFF, MIFF, Postscript, & MNG) which are comprized of multiple image frames. Individual frames of a multi-frame image may be requested by adding array-style notation to the end of the file name (e.g. "animation.gif[3]" retrieves the fourth frame of a GIF animation. Various image manipulation operations may be applied to the image. Attributes may be set on the image to influence the operation of the manipulation operations. The Pixels class provides low-level access to image pixels. As a convenience, including <Magick++.h> is sufficient in order to use the complete Magick++ API. The Magick++ API is enclosed within the Magick namespace so you must either add the prefix " Magick:: " to each class/enumeration name or add the statement " using namespace Magick;" after including the Magick++.h header.

The InitializeMagick() function MUST be invoked before constructing any Magick++ objects. This used to be optional, but now it is absolutely required. This function initalizes semaphores and configuration information necessary for the software to work correctly. Failing to invoke InitializeMagick() is likely to lead to a program crash or thrown assertion. If the program resides in the same directory as the GraphicsMagick files, then argv[0] may be passed as an argument so that GraphicsMagick knows where its files reside, otherwise NULL may be passed and GraphicsMagick will try to use other means (if necessary).

The preferred way to allocate Image objects is via automatic allocation (on the stack). There is no concern that allocating Image objects on the stack will excessively enlarge the stack since Magick++ allocates all large data objects (such as the actual image data) from the heap. Use of automatic allocation is preferred over explicit allocation (via new) since it is much less error prone and allows use of C++ scoping rules to avoid memory leaks. Use of automatic allocation allows Magick++ objects to be assigned and copied just like the C++ intrinsic data types (e.g. 'int '), leading to clear and easy to read code. Use of automatic allocation leads to naturally exception-safe code since if an exception is thrown, the object is automatically deallocated once the stack unwinds past the scope of the allocation (not the case for objects allocated via new ).

Image is very easy to use. For example, here is a the source to a program which reads an image, crops it, and writes it to a new file (the exception handling is optional but strongly recommended):

#include <Magick++.h>
#include <iostream>
using namespace std;
using namespace Magick;
int main(int argc,char **argv)
{
  // Initialize the API.  Can pass NULL if argv is not available.
  InitializeMagick(*argv);

  // Construct the image object. Seperating image construction from the
  // the read operation ensures that a failure to read the image file
  // doesn't render the image object useless.
  Image image;

  try {
    // Determine if Warning exceptions are thrown.
    // Use is optional.  Set to true to block Warning exceptions.
    image.quiet( false );

    // Read a file into image object
    image.read( "girl.gif" );

    // Crop the image to specified size (width, height, xOffset, yOffset)
    image.crop( Geometry(100,100, 100, 100) );

    // Write the image to a file
    image.write( "x.gif" );
  }
  catch( Exception &error_ )
    {
      cout << "Caught exception: " << error_.what() << endl;
      return 1;
    }
  return 0;
}

The following is the source to a program which illustrates the use of Magick++'s efficient reference-counted assignment and copy-constructor operations which minimize use of memory and eliminate unncessary copy operations (allowing Image objects to be efficiently assigned, and copied into containers). The program accomplishes the following:

  1. Read master image.
  2. Assign master image to second image.
  3. Zoom second image to the size 640x480.
  4. Assign master image to a third image.
  5. Zoom third image to the size 800x600.
  6. Write the second image to a file.
  7. Write the third image to a file.
#include <Magick++.h>
#include <iostream>
using namespace std;
using namespace Magick;
int main(int argc,char **argv)
{
    InitializeMagick(*argv);
    Image master("horse.jpg");
    Image second = master;
    second.zoom("640x480");
    Image third = master;
    third.zoom("800x600");
    second.write("horse640x480.jpg");
    third.write("horse800x600.jpg");
    return 0;
}

During the entire operation, a maximum of three images exist in memory and the image data is never copied.

The following is the source for another simple program which creates a 100 by 100 pixel white image with a red pixel in the center and writes it to a file:

#include <Magick++.h>
using namespace std;
using namespace Magick;
int main(int argc,char **argv)
{
    InitializeMagick(*argv);
    Image image( "100x100", "white" );
    image.pixelColor( 49, 49, "red" );
    image.write( "red_pixel.png" );
    return 0;
}

If you wanted to change the color image to grayscale, you could add the lines:

image.quantizeColorSpace( GRAYColorspace );
image.quantizeColors( 256 );
image.quantize( );

or, more simply:

image.type( GrayscaleType );

prior to writing the image.

BLOBs

While encoded images (e.g. JPEG) are most often written-to and read-from a disk file, encoded images may also reside in memory. Encoded images in memory are known as BLOBs (Binary Large OBjects) and may be represented using the Blob class. The encoded image may be initially placed in memory by reading it directly from a file, reading the image from a database, memory-mapped from a disk file, or could be written to memory by Magick++. Once the encoded image has been placed within a Blob, it may be read into a Magick++ Image via a constructor or read() . Likewise, a Magick++ image may be written to a Blob via write().

An example of using Image to write to a Blob follows:

#include <Magick++.h>
using namespace std;
using namespace Magick;
int main(int argc,char **argv)
{
    // Read GIF file from disk
    Image image( "giraffe.gif" );

    // Write to BLOB in JPEG format
    Blob blob;
    image.magick( "JPEG" ) // Set JPEG output format
    image.write( &blob );

    [ Use BLOB data (in JPEG format) here ]

    return 0;
}

likewise, to read an image from a Blob, you could use one of the following examples:

[ Entry condition for the following examples is that data is pointer to encoded image data and length represents the size of the data ]

Blob blob( data, length );
Image image( blob );

or

Blob blob( data, length );
Image image;
image.read( blob);

Some images do not contain their size or format so the size and format must be specified in advance:

Blob blob( data, length );
Image image;
image.size( "640x480")
image.magick( "RGBA" );
image.read( blob);

Construct An Image

An Image may be constructed in a number of ways. It may be constructed from a file, a URL, or an encoded image (e.g. JPEG) contained in an in-memory Blob . The following Image constructors and assignment operators are available:

Construct from image file or image specification:

Image( const std::string &imageSpec_ )

Construct a blank image canvas of specified size and color:

Image( const Geometry &size_, const Color &color_ )

Construct Image from in-memory Blob:

Image ( const Blob &blob_ )

Construct Image of specified size from in-memory Blob:

Image ( const Blob &blob_, const Geometry &size_ )

Construct Image of specified size and depth from in-memory Blob:

Image ( const Blob &blob_, const Geometry &size,
        const unsigned int depth )

Construct Image of specified size, depth, and format from in-memory Blob:

Image ( const Blob &blob_, const Geometry &size,
        const unsigned int depth_,
        const std::string &magick_ )

Construct Image of specified size, and format from in-memory Blob:

Image ( const Blob &blob_, const Geometry &size,
        const std::string &magick_ )

Construct an image based on an array of raw pixels, of specified type and mapping, in memory:

Image ( const unsigned int width_,
        const unsigned int height_,
        const std::string &map_,
        const StorageType type_,
        const void *pixels_ )

Default constructor:

Image( void )

Copy constructor:

Image ( const Image & image_ )

Assignment operator:

Image& operator= ( const Image &image_ )

Read Or Write An Image

ping

Ping is similar to read except only enough of the image is read to determine the image columns, rows, and filesize. Access the columns(), rows(), and fileSize() attributes after invoking ping. Other attributes may also be available. The image pixels are not valid after calling ping:

void            ping ( const std::string &imageSpec_ )

Ping is similar to read except only enough of the image is read to determine the image columns, rows, and filesize. Access the columns(), rows(), and fileSize() attributes after invoking ping. The image pixels are not valid after calling ping:

void            ping ( const Blob &blob_ )

read

Read single image frame into current object. Use ping instead if you want to obtain the basic attributes of the image without reading the whole file/blob:

void            read ( const std::string &imageSpec_ )

Read single image frame of specified size into current object:

void            read ( const Geometry &size_,
                       const std::string &imageSpec_ )

Read single image frame from in-memory Blob:

void            read ( const Blob        &blob_ )

Read single image frame of specified size from in-memory Blob:

void            read ( const Blob        &blob_,
                       const Geometry    &size_ )

Read single image frame of specified size and depth from in-memory Blob:

void            read ( const Blob         &blob_,
                       const Geometry     &size_,
                       const unsigned int depth_ )

Read single image frame of specified size, depth, and format from in-memory Blob:

void            read ( const Blob         &blob_,
                       const Geometry     &size_,
                       const unsigned int depth_,
                       const std::string  &magick_ )

Read single image frame of specified size, and format from in-memory Blob:

void            read ( const Blob         &blob_,
                       const Geometry     &size_,
                       const std::string  &magick_ )

Read single image frame from an array of raw pixels, with specified storage type (ConstituteImage), e.g. image.read( 640, 480, "RGB", 0, pixels ):

void            read ( const unsigned int width_,
                       const unsigned int height_,
                       const std::string &map_,
                       const StorageType  type_,
                       const void        *pixels_ )

write

Write single image frame to a file:

void            write ( const std::string &imageSpec_ )

Write single image frame to in-memory Blob, with optional format and adjoin parameters:

void            write ( Blob *blob_ )

void            write ( Blob *blob_,
                        const std::string &magick_ )

void            write ( Blob *blob_,
                        const std::string &magick_,
                        const unsigned int depth_ )

Write single image frame to an array of pixels with storage type specified by user (DispatchImage), e.g. image.write( 0, 0, 640, 1, "RGB", 0, pixels ):

void            write ( const int x_,
                        const int y_,
                        const unsigned int columns_,
                        const unsigned int rows_,
                        const std::string& map_,
                        const StorageType type_,
                        void *pixels_ )

Manipulate An Image

Image supports access to all the single-image (versus image-list) manipulation operations provided by the GraphicsMagick library. If you must process a multi-image file (such as an animation), the STL interface , which provides a multi-image abstraction on top of Image, must be used.

Image manipulation methods are very easy to use. For example:

Image image;
image.read("myImage.tiff");
image.addNoise(GaussianNoise);
image.write("myImage.tiff");

adds gaussian noise to the image file "myImage.tiff".

The following image manipulation methods are available:

adaptiveThreshold

Apply adaptive thresholding to the image (see http://homepages.inf.ed.ac.uk/rbf/HIPR2/adpthrsh.htm). Adaptive thresholding is useful if the ideal threshold level is not known in advance, or if the illumination gradient is not constant across the image. Adaptive thresholding works by evaulating the mean (average) of a pixel region (size specified by width and height) and using the mean as the thresholding value. In order to remove residual noise from the background, the threshold may be adjusted by subtracting a constant offset (default zero) from the mean to compute the threshold:

void            adaptiveThreshold ( const unsigned int width,
                                    const unsigned int height,
                                    const double offset = 0.0 )

addNoise

Add noise to image with the specified noise type:

void            addNoise ( const NoiseType noiseType_ )

addNoiseChannel

Add noise to an image channel with the specified noise type. The channel parameter specifies the channel to add noise to. The noiseType parameter specifies the type of noise:

void            addNoiseChannel ( const ChannelType channel_,
                                  const NoiseType noiseType_)

affineTransform

Transform image by specified affine (or free transform) matrix:

void            affineTransform ( const DrawableAffine &affine )

annotate

Annotate image (draw text on image)

Gravity effects text placement in bounding area according to these rules:

NorthWestGravity
text bottom-left corner placed at top-left
NorthGravity
text bottom-center placed at top-center
NorthEastGravity
text bottom-right corner placed at top-right
WestGravity
text left-center placed at left-center
CenterGravity
text center placed at center
EastGravity
text right-center placed at right-center
SouthWestGravity
text top-left placed at bottom-left
SouthGravity
text top-center placed at bottom-center
SouthEastGravity
text top-right placed at bottom-right

Annotate using specified text, and placement location:

void            annotate ( const std::string &text_,
                           const Geometry &location_ )

Annotate using specified text, bounding area, and placement gravity:

void            annotate ( const std::string &text_,
                           const Geometry &boundingArea_,
                           const GravityType gravity_ )

Annotate with text using specified text, bounding area, placement gravity, and rotation:

void            annotate ( const std::string &text_,
                           const Geometry &boundingArea_,
                           const GravityType gravity_,
                           const double degrees_ )

Annotate with text (bounding area is entire image) and placement gravity:

void            annotate ( const std::string &text_,
                           const GravityType gravity_ )

autoOrient

Automatically orient image to be right-side up based on its current orientation attribute. This allows the image to be viewed correctly when the orientation attribute is not available, or is not respected:

void            autoOrient( void )

blur

Blur an image with the specified blur factor.

The radius parameter specifies the radius of the Gaussian, in pixels, not counting the center pixel. The sigma parameter specifies the standard deviation of the Laplacian, in pixels:

void            blur ( const double radius_ = 0.0,
                       const double sigma_ = 1.0  )

blurChannel

Blur an image channel with the specified blur factor.

The channel parameter specifies the channel to modify. The radius parameter specifies the radius of the Gaussian, in pixels, not counting the center pixel. The sigma parameter specifies the standard deviation of the Laplacian, in pixels:

void            blurChannel ( const ChannelType channel_,
                              const double radius_ = 0.0,
                              const double sigma_ = 1.0  )

border

Border image (add border to image). The color of the border is specified by the borderColor attribute:

void            border ( const Geometry &geometry_
                         = borderGeometryDefault )

cdl

Bake in the ASC-CDL, which is a convention for the for the exchange of basic primary color grading information between for the exchange of basic primary color grading information between equipment and software from different manufacturers. It is a useful transform for other purposes as well:

void cdl ( const std::string &cdl_ )

See CdlImage for more details on the ASC-CDL.

channel

Extract channel from image. Use this option to extract a particular channel from the image. MatteChannel for example, is useful for extracting the opacity values from an image:

void            channel ( const ChannelType channel_ )

channelDepth

Set or obtain modulus channel depth:

void            channelDepth ( const ChannelType channel_,
                               const unsigned int depth_ )

unsigned int    channelDepth ( const ChannelType channel_ )

charcoal

Charcoal effect image (looks like charcoal sketch).

The radius parameter specifies the radius of the Gaussian, in pixels, not counting the center pixel. The sigma parameter specifies the standard deviation of the Laplacian, in pixels:

void            charcoal ( const double radius_ = 0.0,
                           const double sigma_ = 1.0 )

chop

Chop image (remove vertical or horizontal subregion of image):

void            chop ( const Geometry &geometry_ )

colorize

Colorize image with pen color, using specified percent opacity for red, green, and blue quantums:

void            colorize ( const unsigned int opacityRed_,
                           const unsigned int opacityGreen_,
                           const unsigned int opacityBlue_,
                           const Color &penColor_ )

Colorize image with pen color, using specified percent opacity:

void            colorize ( const unsigned int opacity_,
                           const Color &penColor_ )

colorMatrix

Apply a color matrix to the image channels. The user supplied matrix may be of order 1 to 5 (1x1 through 5x5):

void            colorMatrix (const unsigned int order_,
                             const double *color_matrix_)

See ColorMatrixImage for more details.

comment

Comment image (add comment string to image). By default, each image is commented with its file name. Use this method to assign a specific comment to the image. Optionally you can include the image filename, type, width, height, or other image attributes by embedding special format characters:

void            comment ( const std::string &comment_ )

compare

Compare current image with another image. Sets meanErrorPerPixel, normalizedMaxError, and normalizedMeanError in the current image. False is returned if the images are identical. An ErrorOption exception is thrown if the reference image columns, rows, colorspace, or matte differ from the current image:

bool            compare ( const Image &reference_ )

composite

Compose an image onto another at specified x and y offset and using a specified algorithm:

void            composite ( const Image &compositeImage_,
                            const int xOffset_,
                            const int yOffset_,
                            const CompositeOperator compose_
                            = InCompositeOp )

void            composite ( const Image &compositeImage_,
                            const Geometry &offset_,
                            const CompositeOperator compose_
                            = InCompositeOp )

void            composite ( const Image &compositeImage_,
                            const GravityType gravity_,
                            const CompositeOperator compose_
                            = InCompositeOp )

contrast

Contrast image (enhance intensity differences in image):

void            contrast ( const unsigned int sharpen_ )

convolve

Convolve image. Applies a user-specified convolution to the image. The order parameter represents the number of columns and rows in the filter kernel while kernel is a two-dimensional array of doubles representing the convolution kernel to apply:

void            convolve ( const unsigned int order_,
                           const double *kernel_ )

crop

Crop image (return subregion of original image):

void            crop ( const Geometry &geometry_ )

cycleColormap

Cycle (rotate) image colormap:

void            cycleColormap ( const int amount_ )

despeckle

Despeckle image (reduce speckle noise):

void            despeckle ( void )

display

Display image on screen. Caution: if an image format is is not compatible with the display visual (e.g. JPEG on a colormapped display) then the original image will be altered. Use a copy of the original if this is a problem:

void display ( void )

draw

Draw shape or text on image using a single drawable object:

void            draw ( const Drawable &drawable_ );

Draw shapes or text on image using a set of Drawable objects contained in an STL list. Use of this method improves drawing performance and allows batching draw objects together in a list for repeated use:

void            draw ( const std::list<Magick::Drawable> &drawable_ );

edge

Edge image (hilight edges in image). The radius is the radius of the pixel neighborhood.. Specify a radius of zero for automatic radius selection:

void            edge ( const double radius_ = 0.0 )

emboss

Emboss image (hilight edges with 3D effect). The radius parameter specifies the radius of the Gaussian, in pixels, not counting the center pixel. The sigma parameter specifies the standard deviation of the Laplacian, in pixels:

void            emboss ( const double radius_ = 0.0,
                         const double sigma_ = 1.0)

enhance

Enhance image (minimize noise):

void            enhance ( void );

equalize

Equalize image (histogram equalization):

void            equalize ( void )

erase

Set all image pixels to the current background color:

void            erase ( void )

extent

Create an image canvas using background color sized according to geometry and composite existing image on it, with image placement controlled by gravity. Parameters are obtained from existing image properties if they are not specified via a method parameter. Parameters which are supported by image properties (gravity and backgroundColor) update those image properties as a side-effect:

void            extent ( const Geometry &geometry_ )

void            extent ( const Geometry &geometry_,
                         const GravityType &gravity_ )

void            extent ( const Geometry &geometry_,
                         const Color &backgroundColor_ )

void            extent ( const Geometry &geometry_,
                         const Color &backgroundColor_,
                         const GravityType &gravity_ );

flip

Flip image (reflect each scanline in the vertical direction):

void            flip ( void )

floodFillColor

Flood-fill color across pixels that match the color of the target pixel and are neighbors of the target pixel. Uses current fuzz setting when determining color match:

void            floodFillColor( const unsigned int x_,
                                const unsigned int y_,
                                const Color &fillColor_ )

void            floodFillColor( const Geometry &point_,
                                const Color &fillColor_ )

Flood-fill color across pixels starting at target-pixel and stopping at pixels matching specified border color. Uses current fuzz setting when determining color match:

void            floodFillColor( const unsigned int x_,
                                const unsigned int y_,
                                const Color &fillColor_,
                                const Color &borderColor_ )

void            floodFillColor( const Geometry &point_,
                                const Color &fillColor_,
                                const Color &borderColor_ )

floodFillOpacity

Flood-fill pixels matching color (within fuzz factor) of target pixel(x,y) with replacement opacity value using method:

void            floodFillOpacity ( const unsigned int x_,
                                   const unsigned int y_,
                                   const unsigned int opacity_,
                                   const PaintMethod method_ )

floodFillTexture

Flood-fill texture across pixels that match the color of the target pixel and are neighbors of the target pixel. Uses current fuzz setting when determining color match:

void            floodFillTexture( const unsigned int x_,
                                  const unsigned int y_,
                                  const Image &texture_ )

void            floodFillTexture( const Geometry &point_,
                                  const Image &texture_ )

Flood-fill texture across pixels starting at target-pixel and stopping at pixels matching specified border color. Uses current fuzz setting when determining color match:

void            floodFillTexture( const unsigned int x_,
                                  const unsigned int y_,
                                  const Image &texture_,
                                  const Color &borderColor_ )

void            floodFillTexture( const Geometry &point_,
                                  const Image &texture_,
                                  const Color &borderColor_ )

flop

Flop image (reflect each scanline in the horizontal direction):

void            flop ( void );

frame

Draw a decorative frame around the image:

void            frame ( const Geometry &geometry_ = frameGeometryDefault )

void            frame ( const unsigned int width_,
                        const unsigned int height_,
                        const int innerBevel_ = 6,
                        const int outerBevel_ = 6 )

gamma

Gamma correct the image or individual image channels:

void            gamma ( const double gamma_ )

void            gamma ( const double gammaRed_,
                        const double gammaGreen_,
                        const double gammaBlue_ )

gaussianBlur

Gaussian blur image. The number of neighbor pixels to be included in the convolution mask is specified by width. The standard deviation of the gaussian bell curve is specified by sigma:

void            gaussianBlur ( const double width_, const double sigma_ )

gaussianBlurChannel

Gaussian blur image channel. The number of neighbor pixels to be included in the convolution mask is specified by width. The standard deviation of the gaussian bell curve is specified by sigma:

void            gaussianBlurChannel ( const ChannelType channel_,
                                      const double width_,
                                      const double sigma_ )

implode

Implode image (special effect):

void            implode ( const double factor_ )

haldClut

Apply a color lookup table (Hald CLUT) to the image:

void            haldClut ( const Image &clutImage_ )

See HaldClutImage for more details.

label

Assign a label to an image. Use this option to assign a specific label to the image. Optionally you can include the image filename, type, width, height, or scene number in the label by embedding special format characters. If the first character of string is @, the image label is read from a file titled by the remaining characters in the string. When converting to Postscript, use this option to specify a header string to print above the image:

void            label ( const std::string &label_ )

level

Level image to increase image contrast, and/or adjust image gamma. Adjust the levels of the image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid (gamma), and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point (gamma) specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value. The black and white point have the valid range 0 to MaxRGB while mid (gamma) has a useful range of 0 to ten:

void            level ( const double black_point,
                        const double white_point,
                        const double mid_point=1.0 )

levelChannel

Level image channel to increase image contrast, and/or adjust image gamma. Adjust the levels of the image channel by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid (gamma), and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point (gamma) specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value. The black and white point have the valid range 0 to MaxRGB while mid (gamma) has a useful range of 0 to ten:

void            levelChannel ( const ChannelType channel,
                               const double black_point,
                               const double white_point,
                               const double mid_point=1.0 )

magnify

Magnify image by integral size (double the dimensions):

void            magnify ( void )

map

Remap image colors with closest color from a reference image. Set dither to true in to apply Floyd/Steinberg error diffusion to the image. By default, color reduction chooses an optimal set of colors that best represent the original image. Alternatively, you can choose a particular set of colors from an image file with this option:

void            map ( const Image &mapImage_ ,
                      const bool dither_ = false )

matteFloodfill

Floodfill designated area with a replacement opacity value:

void            matteFloodfill ( const Color &target_ ,
                                 const unsigned int opacity_,
                                 const int x_, const int y_,
                                 const PaintMethod method_ )

medianFilter

Filter image by replacing each pixel component with the median color in a circular neighborhood:

void            medianFilter ( const double radius_ = 0.0 )

minify

Reduce image by integral (half) size:

void            minify ( void )

modifyImage

Prepare to update image (copy if reference > 1). Normally Magick++'s implicit reference counting takes care of all instance management. In the rare case that the automatic instance management does not work, use this method to assure that there is only one reference to the image to be modified. It should be used in the cases where a GraphicsMagick C function is used directly on an image which may have multiple references:

void            modifyImage ( void )

modulate

Modulate percent hue, saturat