wand.image — Image objects

Opens and manipulates images. Image objects can be used in with statement, and these resources will be automatically managed (even if any error happened):

with Image(filename='pikachu.png') as i:
    print 'width =', i.width
    print 'height =', i.height
wand.image.ALPHA_CHANNEL_TYPES = ('undefined', 'activate', 'background', 'copy', 'deactivate', 'extract', 'opaque', 'reset', 'set', 'shape', 'transparent', 'flatten', 'remove')

(tuple) The list of alpha channel types

  • 'undefined'
  • 'activate'
  • 'background'
  • 'copy'
  • 'deactivate'
  • 'extract'
  • 'opaque'
  • 'reset'
  • 'set'
  • 'shape'
  • 'transparent'
  • 'flatten'
  • 'remove'

See also

ImageMagick Image Channel Describes the SetImageAlphaChannel method which can be used to modify alpha channel. Also describes AlphaChannelType

wand.image.CHANNELS = {'opacity': 8, 'true_alpha': 64, 'gray': 1, 'rgb_channels': 128, 'yellow': 4, 'sync_channels': 256, 'default_channels': 134217719, 'alpha': 8, 'cyan': 1, 'magenta': 2, 'undefined': 0, 'blue': 4, 'index': 32, 'gray_channels': 128, 'composite_channels': 47, 'green': 2, 'all_channels': 134217727, 'black': 32, 'red': 1}

(dict) The dictionary of channel types.

  • 'undefined'
  • 'red'
  • 'gray'
  • 'cyan'
  • 'green'
  • 'magenta'
  • 'blue'
  • 'yellow'
  • 'alpha'
  • 'opacity'
  • 'black'
  • 'index'
  • 'composite_channels'
  • 'all_channels'
  • 'true_alpha'
  • 'rgb_channels'
  • 'gray_channels'
  • 'sync_channels'
  • 'default_channels'

See also

ImageMagick Color Channels
Lists the various channel types with descriptions of each
wand.image.COMPOSITE_OPS = ('undefined', 'no', 'add', 'atop', 'blend', 'bumpmap', 'change_mask', 'clear', 'color_burn', 'color_dodge', 'colorize', 'copy_black', 'copy_blue', 'copy', 'copy_cyan', 'copy_green', 'copy_magenta', 'copy_opacity', 'copy_red', 'copy_yellow', 'darken', 'dst_atop', 'dst', 'dst_in', 'dst_out', 'dst_over', 'difference', 'displace', 'dissolve', 'exclusion', 'hard_light', 'hue', 'in', 'lighten', 'linear_light', 'luminize', 'minus', 'modulate', 'multiply', 'out', 'over', 'overlay', 'plus', 'replace', 'saturate', 'screen', 'soft_light', 'src_atop', 'src', 'src_in', 'src_out', 'src_over', 'subtract', 'threshold', 'xor', 'divide')

(tuple) The list of composition operators

  • 'undefined'
  • 'no'
  • 'add'
  • 'atop'
  • 'blend'
  • 'bumpmap'
  • 'change_mask'
  • 'clear'
  • 'color_burn'
  • 'color_dodge'
  • 'colorize'
  • 'copy_black'
  • 'copy_blue'
  • 'copy'
  • 'copy_cyan'
  • 'copy_green'
  • 'copy_magenta'
  • 'copy_opacity'
  • 'copy_red'
  • 'copy_yellow'
  • 'darken'
  • 'dst_atop'
  • 'dst'
  • 'dst_in'
  • 'dst_out'
  • 'dst_over'
  • 'difference'
  • 'displace'
  • 'dissolve'
  • 'exclusion'
  • 'hard_light'
  • 'hue'
  • 'in'
  • 'lighten'
  • 'linear_light'
  • 'luminize'
  • 'minus'
  • 'modulate'
  • 'multiply'
  • 'out'
  • 'over'
  • 'overlay'
  • 'plus'
  • 'replace'
  • 'saturate'
  • 'screen'
  • 'soft_light'
  • 'src_atop'
  • 'src'
  • 'src_in'
  • 'src_out'
  • 'src_over'
  • 'subtract'
  • 'threshold'
  • 'xor'
  • 'divide'

See also

ImageMagick Composition Operators
Demonstrates the results of applying the various composition composition operators.
wand.image.EVALUATE_OPS = ('undefined', 'add', 'and', 'divide', 'leftshift', 'max', 'min', 'multiply', 'or', 'rightshift', 'set', 'subtract', 'xor', 'pow', 'log', 'threshold', 'thresholdblack', 'thresholdwhite', 'gaussiannoise', 'impulsenoise', 'laplaciannoise', 'multiplicativenoise', 'poissonnoise', 'uniformnoise', 'cosine', 'sine', 'addmodulus', 'mean', 'abs', 'exponential', 'median', 'sum')

(tuple) The list of evaluation operators

  • 'undefined'
  • 'add'
  • 'and'
  • 'divide'
  • 'leftshift'
  • 'max'
  • 'min'
  • 'multiply'
  • 'or'
  • 'rightshift'
  • 'set'
  • 'subtract'
  • 'xor'
  • 'pow'
  • 'log'
  • 'threshold'
  • 'thresholdblack'
  • 'thresholdwhite'
  • 'gaussiannoise'
  • 'impulsenoise'
  • 'laplaciannoise'
  • 'multiplicativenoise'
  • 'poissonnoise'
  • 'uniformnoise'
  • 'cosine'
  • 'sine'
  • 'addmodulus'
  • 'mean'
  • 'abs'
  • 'exponential'
  • 'median'
  • 'sum'

See also

ImageMagick Image Evaluation Operators
Describes the MagickEvaluateImageChannel method and lists the various evaluations operators
wand.image.FILTER_TYPES = ('undefined', 'point', 'box', 'triangle', 'hermite', 'hanning', 'hamming', 'blackman', 'gaussian', 'quadratic', 'cubic', 'catrom', 'mitchell', 'jinc', 'sinc', 'sincfast', 'kaiser', 'welsh', 'parzen', 'bohman', 'bartlett', 'lagrange', 'lanczos', 'lanczossharp', 'lanczos2', 'lanczos2sharp', 'robidoux', 'robidouxsharp', 'cosine', 'spline', 'sentinel')

(tuple) The list of filter types.

  • 'undefined'
  • 'point'
  • 'box'
  • 'triangle'
  • 'hermite'
  • 'hanning'
  • 'hamming'
  • 'blackman'
  • 'gaussian'
  • 'quadratic'
  • 'cubic'
  • 'catrom'
  • 'mitchell'
  • 'jinc'
  • 'sinc'
  • 'sincfast'
  • 'kaiser'
  • 'welsh'
  • 'parzen'
  • 'bohman'
  • 'bartlett'
  • 'lagrange'
  • 'lanczos'
  • 'lanczossharp'
  • 'lanczos2'
  • 'lanczos2sharp'
  • 'robidoux'
  • 'robidouxsharp'
  • 'cosine'
  • 'spline'
  • 'sentinel'

See also

ImageMagick Resize Filters
Demonstrates the results of resampling images using the various resize filters and blur settings available in ImageMagick.
wand.image.IMAGE_TYPES = ('undefined', 'bilevel', 'grayscale', 'grayscalematte', 'palette', 'palettematte', 'truecolor', 'truecolormatte', 'colorseparation', 'colorseparationmatte', 'optimize', 'palettebilevelmatte')

(tuple) The list of image types

  • 'undefined'
  • 'bilevel'
  • 'grayscale'
  • 'grayscalematte'
  • 'palette'
  • 'palettematte'
  • 'truecolor'
  • 'truecolormatte'
  • 'colorseparation'
  • 'colorseparationmatte'
  • 'optimize'
  • 'palettebilevelmatte'

See also

ImageMagick Image Types
Describes the MagickSetImageType method which can be used to set the type of an image
wand.image.UNIT_TYPES = ('undefined', 'pixelsperinch', 'pixelspercentimeter')

(tuple) The list of resolution unit types

  • 'undefined'
  • 'pixelsperinch'
  • 'pixelspercentimeter'

See also

ImageMagick Image Units
Describes the MagickSetImageUnits method which can be used to set image units of resolution
exception wand.image.ClosedImageError

An error that rises when some code tries access to an already closed image.

class wand.image.Image(image=None, blob=None, file=None, filename=None, format=None, width=None, height=None, background=None)

An image object.

Parameters:
  • image (Image) – makes an exact copy of the image
  • blob (str) – opens an image of the blob byte array
  • file (file object) – opens an image of the file object
  • filename (basestring) – opens an image of the filename string
  • format (basestring) – forces filename to buffer.``format`` to help imagemagick detect the file format. Used only in blob or file cases
  • width (numbers.Integral) – the width of new blank image.
  • height (numbers.Integral) – the height of new blank imgage.
  • background (wand.color.Color) – an optional background color. default is transparent

New in version 0.1.5: The file parameter.

New in version 0.1.1: The blob parameter.

New in version 0.2.1: The format parameter.

New in version 0.2.2: The width, height, background parameters.

[left:right, top:bottom]

Crops the image by its left, right, top and bottom, and then returns the cropped one.

with img[100:200, 150:300] as cropped:
    # manipulated the cropped image
    pass

Like other subscriptable objects, default is 0 or its width/height:

img[:, :]        #--> just clone
img[:100, 200:]  #--> equivalent to img[0:100, 200:img.height]

Negative integers count from the end (width/height):

img[-70:-50, -20:-10]
#--> equivalent to img[width-70:width-50, height-20:height-10]
Returns :the cropped image
Rtype :Image

New in version 0.1.2.

alpha_channel

(bool) Get state of image alpha channel. It can also be used to enable/disable alpha channel.

New in version 0.2.1.

background_color

(wand.color.Color) The image background color. It can also be set to change the background color.

New in version 0.1.9.

clone()

Clones the image. It is equivalent to call Image with image parameter.

with img.clone() as cloned:
    # manipulate the cloned image
    pass
Returns:the cloned new image
Return type:Image

New in version 0.1.1.

close()

Closes the image explicitly. If you use the image object in with statement, it was called implicitly so don’t have to call it.

Note

It has the same functionality of destroy() method.

composite(image, left, top)

Places the supplied image over the current image, with the top left corner of image at coordinates left, top of the current image. The dimensions of the current image are not changed.

Parameters:

New in version 0.2.0.

compression_quality

(numbers.Integral) Compression quality of this image.

New in version 0.2.0.

convert(format)

Converts the image format with the original image maintained. It returns a converted image instance which is new.

with img.convert('png') as converted:
    converted.save(filename='converted.png')
Parameters:format (basestring) – image format to convert to
Returns:a converted image
Return type:Image
Raises :ValueError when the given format is unsupported

New in version 0.1.6.

crop(left=0, top=0, right=None, bottom=None, width=None, height=None, reset_coords=True)

Crops the image in-place.

+--------------------------------------------------+
|              ^                         ^         |
|              |                         |         |
|             top                        |         |
|              |                         |         |
|              v                         |         |
| <-- left --> +-------------------+  bottom       |
|              |             ^     |     |         |
|              | <-- width --|---> |     |         |
|              |           height  |     |         |
|              |             |     |     |         |
|              |             v     |     |         |
|              +-------------------+     v         |
| <--------------- right ---------->               |
+--------------------------------------------------+
Parameters:
  • left (numbers.Integral) – x-offset of the cropped image. default is 0
  • top (numbers.Integral) – y-offset of the cropped image. default is 0
  • right (numbers.Integral) – second x-offset of the cropped image. default is the width of the image. this parameter and width parameter are exclusive each other
  • bottom (numbers.Integral) – second y-offset of the cropped image. default is the height of the image. this parameter and height parameter are exclusive each other
  • width (numbers.Integral) – the width of the cropped image. default is the width of the image. this parameter and right parameter are exclusive each other
  • height (numbers.Integral) – the height of the cropped image. default is the height of the image. this parameter and bottom parameter are exclusive each other
  • reset_coords (bool) – optional flag. If set, after the rotation, the coordinate frame will be relocated to the upper-left corner of the new image. By default is True.
Raises exceptions.ValueError:
 

when one or more arguments are invalid

Note

If you want to crop the image but not in-place, use slicing operator.

Changed in version 0.1.8: Made to raise ValueError instead of IndexError for invalid width/height arguments.

New in version 0.1.7.

depth

(numbers.Integral) The depth of this image.

New in version 0.2.1.

format

(basestring) The image format.

If you want to convert the image format, just reset this property:

assert isinstance(img, wand.image.Image)
img.format = 'png'

It may raise ValueError when the format is unsupported.

See also

ImageMagick Image Formats
ImageMagick uses an ASCII string known as magick (e.g. GIF) to identify file formats, algorithms acting as formats, built-in patterns, and embedded profile types.

New in version 0.1.6.

height

(numbers.Integral) The height of this image.

make_blob(format=None)

Makes the binary string of the image.

Parameters:format (basestring) – the image format to write e.g. 'png', 'jpeg'. it is omittable
Returns:a blob (bytes) string
Return type:str
Raises :ValueError when format is invalid

Changed in version 0.1.6: Removed a side effect that changes the image format silently.

New in version 0.1.5: The format parameter became optional.

New in version 0.1.1.

mimetype

(basestring) The MIME type of the image e.g. 'image/jpeg', 'image/png'.

New in version 0.1.7.

quantum_range

(int) The maxumim value of a color channel that is supported by the imagemgick library.

New in version 0.2.0.

reset_coords()

Reset the coordinate frame of the image so to the upper-left corner is (0, 0) again (crop and rotate operations change it).

New in version 0.2.0.

resize(width=None, height=None, filter='undefined', blur=1)

Resizes the image.

Parameters:
  • width (numbers.Integral) – the width in the scaled image. default is the original width
  • height (numbers.Integral) – the height in the scaled image. default is the original height
  • filter (basestring, numbers.Integral) – a filter type to use for resizing. choose one in FILTER_TYPES. default is 'undefined' which means IM will try to guess best one to use
  • blur (numbers.Real) – the blur factor where > 1 is blurry, < 1 is sharp. default is 1

Changed in version 0.2.1: The default value of filter has changed from 'triangle' to 'undefined' instead.

Changed in version 0.1.8: The blur parameter changed to take numbers.Real instead of numbers.Rational.

New in version 0.1.1.

rotate(degree, background=None, reset_coords=True)

Rotates the image right. It takes a background color for degree that isn’t a multiple of 90.

Parameters:
  • degree (numbers.Real) – a degree to rotate. multiples of 360 affect nothing
  • background (wand.color.Color) – an optional background color. default is transparent
  • reset_coords (bool) – optional flag. If set, after the rotation, the coordinate frame will be relocated to the upper-left corner of the new image. By default is True.

New in version 0.2.0: The reset_coords parameter.

New in version 0.1.8.

save(file=None, filename=None)

Saves the image into the file or filename. It takes only one argument at a time.

Parameters:
  • file (file object) – a file object to write to
  • filename (basename) – a filename string to write to

New in version 0.1.5: The file parameter.

New in version 0.1.1.

signature

(str) The SHA-256 message digest for the image pixel stream.

New in version 0.1.9.

size

(tuple) The pair of (width, height).

strip()

Strips an image of all profiles and comments.

New in version 0.2.0.

transform(crop='', resize='')

Transforms the image using MagickTransformImage(), which is a convenience function accepting geometry strings to perform cropping and resizing. Cropping is performed first, followed by resizing. Either or both arguments may be omitted or given an empty string, in which case the corresponding action will not be performed. Geometry specification strings are defined as follows:

A geometry string consists of a size followed by an optional offset. The size is specified by one of the options below, where bold terms are replaced with appropriate integer values:

scale%
Height and width both scaled by specified percentage
scale-x%xscale-y%
Height and width individually scaled by specified percentages. Only one % symbol is needed.
width
Width given, height automagically selected to preserve aspect ratio.
xheight
Height given, width automagically selected to preserve aspect ratio.
widthxheight
Maximum values of width and height given; aspect ratio preserved.
widthxheight!
Width and height emphatically given; original aspect ratio ignored.
widthxheight>
Shrinks images with dimension(s) larger than the corresponding width and/or height dimension(s).
widthxheight<
Enlarges images with dimensions smaller than the corresponding width and/or height dimension(s).
area@
Resize image to have the specified area in pixels. Aspect ratio is preserved.

The offset, which only applies to the cropping geometry string, is given by {+-}x{+-}y, that is, one plus or minus sign followed by an x offset, followed by another plus or minus sign, followed by a y offset. Offsets are in pixels from the upper left corner of the image. Negative offsets will cause the corresponding number of pixels to be removed from the right or bottom edge of the image, meaning the cropped size will be the computed size minus the absolute value of the offset.

For example, if you want to crop your image to 300x300 pixels and then scale it by 2x for a final size of 600x600 pixels, you can call:

image.transform('300x300', '200%')

This method is a fairly thing wrapper for the C API, and does not perform any additional checking of the parameters except insofar as verifying that they are of the correct type. Thus, like the C API function, the method is very permissive in terms of what it accepts for geometry strings; unrecognized strings and trailing characters will be ignored rather than raising an error.

Parameters:
  • crop (basestring) – A geometry string defining a subregion of the image to crop to
  • resize (basestring) – A geometry string defining the final size of the image

Note

#104 reported that transform() leaks memory under version 0.3.0, so be careful when you use it on long-running process like web server.

See also

ImageMagick Geometry Specifications
Cropping and resizing geometry for the transform method are specified according to ImageMagick’s geometry string format. The ImageMagick documentation provides more information about geometry strings.

New in version 0.2.2.

transparentize(transparency)

Makes the image transparent by subtracting some percentage of the black color channel. The transparency parameter specifies the percentage.

Parameters:transparency (numbers.Real) – the percentage fade that should be performed on the image, from 0.0 to 1.0

New in version 0.2.0.

trim()

Remove solid border from image. Uses top left pixel as a guide.

New in version 0.2.1.

type

(basestring) The image type.

Defines image type as in wand.image.IMAGE_TYPES enumeration.

It may raise ValueError when the type is unknown.

New in version 0.2.2.

units

(basestring) The resolution units of this image.

wand

Internal pointer to the MagickWand instance. It may raise ClosedImageError when the instance has destroyed already.

watermark(image, transparency=0.0, left=0, top=0)

Transparentized the supplied image and places it over the current image, with the top left corner of image at coordinates left, top of the current image. The dimensions of the current image are not changed.

Parameters:
  • image (wand.image.Image) – the image placed over the current image
  • transparency (numbers.Real) – the percentage fade that should be performed on the image, from 0.0 to 1.0
  • left (numbers.Integral) – the x-coordinate where image will be placed
  • top (numbers.Integral) – the y-coordinate where image will be placed

New in version 0.2.0.

width

(numbers.Integral) The width of this image.

class wand.image.Iterator(image=None, iterator=None)

Row iterator for Image. It shouldn’t be instantiated directly; instead, it can be acquired through Image instance:

assert isinstance(image, wand.image.Image)
iterator = iter(image)

It doesn’t iterate every pixel, but rows. For example:

for row in image:
    for col in row:
        assert isinstance(col, wand.color.Color)
        print col

Every row is a collections.Sequence which consists of one or more wand.color.Color values.

Parameters:image (Image) – the image to get an iterator

New in version 0.1.3.

clone()

Clones the same iterator.

Related Topics

This Page