Wand

Latest PyPI version Documentation Status Build Status Coverage Status

Wand is a ctypes-based simple ImageMagick binding for Python.

from wand.image import Image
from wand.display import display

with Image(filename='mona-lisa.png') as img:
    print(img.size)
    for r in 1, 2, 3:
        with img.clone() as i:
            i.resize(int(i.width * r * 0.25), int(i.height * r * 0.25))
            i.rotate(90 * r)
            i.save(filename='mona-lisa-{0}.png'.format(r))
            display(i)

You can install it from PyPI (and it requires MagickWand library):

$ apt-get install libmagickwand-dev
$ pip install Wand

Why just another binding?

There are already many MagickWand API bindings for Python, however they are lacking something we need:

  • Pythonic and modern interfaces
  • Good documentation
  • Binding through ctypes (not C API) — we are ready to go PyPy!
  • Installation using pip

Requirements

  • Python 2.6 or higher
    • CPython 2.6 or higher
    • CPython 3.2 or higher
    • PyPy 1.5 or higher
  • MagickWand library
    • libmagickwand-dev for APT on Debian/Ubuntu
    • imagemagick for MacPorts/Homebrew on Mac
    • ImageMagick-devel for Yum on CentOS

User’s guide

What’s new in Wand 0.4?

This guide doesn’t cover all changes in 0.4. See also the full list of changes in Version 0.4.0.

Complete Drawing API

Although Wand 0.3 introduced some basic facilities to draw Lines or Texts, these were incomplete.

Since Wand 0.4 wand.drawing it became almost complete. For more detail example, see the drawing guide:

Eric McConville did whole of the work alone (#194), huge thanks for his effort!

Installation

Wand itself can be installed from PyPI using pip:

$ pip install Wand

Wand is a Python binding of ImageMagick, so you have to install it as well:

Note

Wand yet doesn’t support ImageMagick 7 which has several incompatible APIs with previous versions. For more details, see the issue #287.

Or you can simply install Wand and its entire dependencies using the package manager of your system (it’s way convenient but the version might be outdated):

Install ImageMagick on Debian/Ubuntu

If you’re using Linux distributions based on Debian like Ubuntu, it can be easily installed using APT:

$ sudo apt-get install libmagickwand-dev

If you need SVG, WMF, OpenEXR, DjVu, and Graphviz support you have to install libmagickcore5-extra as well:

$ sudo apt-get install libmagickcore5-extra

Install ImageMagick on Fedora/CentOS

If you’re using Linux distributions based on Redhat like Fedora or CentOS, it can be installed using Yum:

$ yum update
$ yum install ImageMagick-devel

Install ImageMagick on Mac

You need one of Homebrew or MacPorts to install ImageMagick.

Homebrew
$ brew install imagemagick

If seam carving (Image.liquid_rescale()) is needed you have install liblqr as well:

$ brew install imagemagick --with-liblqr
MacPorts
$ sudo port install imagemagick

If your Python in not installed using MacPorts, you have to export MAGICK_HOME path as well. Because Python that is not installed using MacPorts doesn’t look up /opt/local, the default path prefix of MacPorts packages.

$ export MAGICK_HOME=/opt/local

Install ImageMagick on Windows

You could build ImageMagick by yourself, but it requires a build tool chain like Visual Studio to compile it. The easiest way is simply downloading a prebuilt binary of ImageMagick for your architecture (win32 or win64).

You can download it from the following link:

http://legacy.imagemagick.org/script/binary-releases.php#windows

Choose a binary for your architecture:

Windows 32-bit
ImageMagick-6.9.x-x-Q16-x86-dll.exe
Windows 64-bit
ImageMagick-6.9.x-x-Q16-x64-dll.exe
_images/windows-setup.png

Note that you have to check Install development headers and libraries for C and C++ to make Wand able to link to it.

_images/windows-envvar.png

Lastly you have to set MAGICK_HOME environment variable to the path of ImageMagick (e.g. C:\Program Files\ImageMagick-6.9.3-Q16). You can set it in Computer ‣ Properties ‣ Advanced system settings ‣ Advanced ‣ Environment Variables….

Install Wand on Debian/Ubuntu

Wand itself is already packaged in Debian/Ubuntu APT repository: python-wand. You can install it using apt-get command:

$ sudo apt-get install python-wand

Install Wand on Fedora

Wand itself is already packaged in Fedora package DB: python-wand. You can install it using dnf command:

$ dnf install python-wand   # Python 2
$ dnf install python3-wand  # Python 3

Install Wand on FreeBSD

Wand itself is already packaged in FreeBSD ports collection: py-wand. You can install it using pkg_add command:

$ pkg_add -r py-wand

Reading images

There are several ways to open images:

All of these operations are provided by the constructor of Image class.

Open an image file

The most frequently used way is just to open an image by its filename. Image’s constructor can take the parameter named filename:

from __future__ import print_function
from wand.image import Image

with Image(filename='pikachu.png') as img:
    print('width =', img.width)
    print('height =', img.height)

Note

It must be passed by keyword argument exactly. Because the constructor has many parameters that are exclusive to each other.

There is a keyword argument named file as well, but don’t confuse it with filename. While filename takes a string of a filename, file takes a input stream (file-like object).

Read a input stream

If an image to open cannot be located by a filename but can be read through input stream interface (e.g. opened by os.popen(), contained in StringIO, read by urllib2.urlopen()), it can be read by Image constructor’s file parameter. It takes all file-like objects which implements read() method:

from __future__ import print_function
from urllib2 import urlopen
from wand.image import Image

response = urlopen('https://stylesha.re/minhee/29998/images/100x100')
try:
    with Image(file=response) as img:
        print('format =', img.format)
        print('size =', img.size)
finally:
    response.close()

In the above example code, response object returned by urlopen() function has read() method, so it also can be used as an input stream for a downloaded image.

Read a blob

If you have just a binary string (str) of the image, you can pass it into Image constructor’s blob parameter to read:

from __future__ import print_function
from wand.image import Image

with open('pikachu.png') as f:
    image_binary = f.read()

with Image(blob=image_binary) as img:
    print('width =', img.width)
    print('height =', img.height)

It is a way of the lowest level to read an image. There will probably not be many cases to use it.

Clone an image

If you have an image already and have to copy it for safe manipulation, use clone() method:

from wand.image import Image

with Image(filename='pikachu.png') as original:
    with original.clone() as converted:
        converted.format = 'png'
        # operations on a converted image...

For some operations like format converting or cropping, there are safe methods that return a new image of manipulated result like convert() or slicing operator. So the above example code can be replaced by:

from wand.image import Image

with Image(filename='pikachu.png') as original:
    with original.convert('png') as converted:
        # operations on a converted image...

Hint file format

When it’s read from a binary string or a file object, you can explicitly give the hint which indicates file format of an image to read — optional format keyword is for that:

from wand.image import Image

with Image(blob=image_binary, format='ico') as image:
    print(image.format)

New in version 0.2.1: The format parameter to Image constructor.

Open an empty image

To open an empty image, you have to set its width and height:

from wand.image import Image

with Image(width=200, height=100) as img:
    img.save(filename='200x100-transparent.png')

Its background color will be transparent by default. You can set background argument as well:

from wand.color import Color
from wand.image import Image

with Color('red') as bg:
    with Image(width=200, height=100, background=bg) as img:
        img.save(filename='200x100-red.png')

New in version 0.2.2: The width, height, and background parameters to Image constructor.

Writing images

You can write an Image object into a file or a byte string buffer (blob) as format what you want.

Convert images to JPEG

If you wonder what is image’s format, use format property.

>>> image.format
'JPEG'

The format property is writable, so you can convert images by setting this property.

from wand.image import Image

with Image(filename='pikachu.png') as img:
    img.format = 'jpeg'
    # operations to a jpeg image...

If you want to convert an image without any changes of the original, use convert() method instead:

from wand.image import Image

with Image(filename='pikachu.png') as original:
    with original.convert('jpeg') as converted:
        # operations to a jpeg image...
        pass

Note

Support for some of the formats are delegated to libraries or external programs. To get a complete listing of which image formats are supported on your system, use identify command provided by ImageMagick:

$ identify -list format

Save to file

In order to save an image to a file, use save() method with the keyword argument filename:

from wand.image import Image

with Image(filename='pikachu.png') as img:
    img.format = 'jpeg'
    img.save(filename='pikachu.jpg')

Note

The image format does not effect the file being saved, to save with a given colorspace use:

from wand.image import Image

with Image(filename='pikachu.jpg') as img:
    img.format = 'jpeg'
    img.save(filename='PNG24:pikachu.png')

Save to stream

You can write an image into a output stream (file-like object which implements write() method) as well. The parameter file takes a such object (it also is the first positional parameter of save() method).

For example, the following code converts pikachu.png image into JPEG, gzips it, and then saves it to pikachu.jpg.gz:

import gzip
from wand.image import Image

gz = gzip.open('pikachu.jpg.gz')
with Image(filename='pikachu.png') as img:
    img.format = 'jpeg'
    img.save(file=gz)
gz.close()

Get binary string

Want just a binary string of the image? Use make_blob() method so:

from wand.image import Image

with image(filename='pikachu.png') as img:
    img.format = 'jpeg'
    jpeg_bin = img.make_blob()

There’s the optional format parameter as well. So the above example code can be simpler:

from wand.image import Image

with Image(filename='pikachu.png') as img:
    jpeg_bin = img.make_blob('jpeg')

Resizing and cropping

Creating thumbnails (by resizing images) and cropping are most frequent works about images. This guide explains ways to deal with sizes of images.

Above all, to get the current size of the image check width and height properties:

>>> from urllib.request import urlopen
>>> from wand.image import Image
>>> f = urlopen('http://pbs.twimg.com/profile_images/712673855341367296/WY6aLbBV_normal.jpg')
>>> with Image(file=f) as img:
...     width = img.width
...     height = img.height
...
>>> f.close()
>>> width
48
>>> height
48

If you want the pair of (width, height), check size property also.

Note

These three properties are all readonly.

Resize images

It scales an image into a desired size even if the desired size is larger than the original size. ImageMagick provides so many algorithms for resizing. The constant FILTER_TYPES contains names of filtering algorithms.

See also

ImageMagick Resize Filters
Demonstrates the results of resampling three images using the various resize filters and blur settings available in ImageMagick, and the file size of the resulting thumbnail images.

Image.resize() method takes width and height of a desired size, optional filter ('undefined' by default which means IM will try to guess best one to use) and optional blur (default is 1). It returns nothing but resizes itself in-place.

>>> img.size
(500, 600)
>>> img.resize(50, 60)
>>> img.size
(50, 60)

Sample images

Although Image.resize() provides many filter options, it’s relatively slow. If speed is important for the job, you’d better use Image.sample() instead. It works in similar way to Image.resize() except it doesn’t provide filter and blur options:

>>> img.size
(500, 600)
>>> img.sample(50, 60)
>>> img.size
(50, 60)

Crop images

To extract a sub-rectangle from an image, use the crop() method. It crops the image in-place. Its parameters are left, top, right, bottom in order.

>>> img.size
(200, 300)
>>> img.crop(10, 20, 50, 100)
>>> img.size
(40, 80)

It can also take keyword arguments width and height. These parameters replace right and bottom.

>>> img.size
(200, 300)
>>> img.crop(10, 20, width=40, height=80)
>>> img.size
(40, 80)

There is an another way to crop images: slicing operator. You can crop an image by [left:right, top:bottom] with maintaining the original:

>>> img.size
(300, 300)
>>> with img[10:50, 20:100] as cropped:
...     print(cropped.size)
...
(40, 80)
>>> img.size
(300, 300)

Specifying gravity along with width and height keyword arguments allows a simplified cropping alternative.

>>> img.size
(300, 300)
>>> img.crop(width=40, height=80, gravity='center')
>>> img.size
(40, 80)

Transform images

Use this function to crop and resize and image at the same time, using ImageMagick geometry strings. Cropping is performed first, followed by resizing.

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:

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

Other example calls:

# crop top left corner
img.transform('50%')

# scale height to 100px and preserve aspect ratio
img.transform(resize='x100')

# if larger than 640x480, fit within box, preserving aspect ratio
img.transform(resize='640x480>')

# crop a 320x320 square starting at 160x160 from the top left
img.transform(crop='320+160+160')

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.

Seam carving (also known as content-aware resizing)

New in version 0.3.0.

Seam carving is an algorithm for image resizing that functions by establishing a number of seams (paths of least importance) in an image and automatically removes seams to reduce image size or inserts seams to extend it.

In short: you can magickally resize images without distortion! See the following examples:

Original Resized
seam.jpg seam-resize.jpg
Cropped Seam carving
seam-crop.jpg seam-liquid.jpg

You can easily rescale images with seam carving using Wand: use Image.liquid_rescale() method:

>>> image = Image(filename='seam.jpg')
>>> image.size
(320, 234)
>>> with image.clone() as resize:
...     resize.resize(234, 234)
...     resize.save(filename='seam-resize.jpg')
...     resize.size
...
(234, 234)
>>> with image[:234, :] as crop:
...     crop.save(filename='seam-crop.jpg')
...     crop.size
...
(234, 234)
>>> with image.clone() as liquid:
...     liquid.liquid_rescale(234, 234)
...     liquid.save(filename='seam-liquid.jpg')
...     liquid.size
...
(234, 234)

Note

It may raise MissingDelegateError if your ImageMagick is configured --without-lqr option. In this case you should recompile ImageMagick.

See also

Seam carving — Wikipedia
The article which explains what seam carving is on Wikipedia.

Note

The image seam.jpg used in the above example is taken by D. Sharon Pruitt and licensed under CC-BY-2.0. It can be found the original photography from Flickr.

Transformation

Note

The image transform.jpg used in this docs is taken by Megan Trace, and licensed under CC BY-NC 2.0. It can be found the original photography from Flickr.

Rotation

New in version 0.1.8.

Image object provides a simple method to rotate images: rotate(). It takes a degree which can be 0 to 359. (Actually you can pass 360, 361, or more but it will be the same to 0, 1, or more respectively.)

For example, where the given image transform.jpg:

transform.jpg

The below code makes the image rotated 90° to right:

from wand.image import Image

with Image(filename='transform.jpg') as image:
    with image.clone() as rotated:
        rotated.rotate(90)
        rotated.save(filename='transform-rotated-90.jpg')

The generated image transform-rotated-90.jpg looks like:

transform-rotated-90.jpg

If degree is not multiples of 90, the optional parameter background will help (its default is transparent):

from wand.color import Color
from wand.image import Image

with Image(filename='transform.jpg') as image:
    with image.clone() as rotated:
        rotated.rotate(135, background=Color('rgb(229,221,112)'))
        rotated.save(filename='transform-rotated-135.jpg')

The generated image transform-rotated-135.jpg looks like:

transform-rotated-135.jpg

Flip and flop

New in version 0.3.0.

You can make a mirror image by reflecting the pixels around the central x- or y-axis. For example, where the given image transform.jpg:

transform.jpg

The following code flips the image using Image.flip() method:

from wand.image import Image

with Image(filename='transform.jpg') as image:
    with image.clone() as flipped:
        flipped.flip()
        flipped.save(filename='transform-flipped.jpg')

The image transform-flipped.jpg generated by the above code looks like:

transform-flipped.jpg

As like flip(), flop() does the same thing except it doesn’t make a vertical mirror image but horizontal:

from wand.image import Image

with Image(filename='transform.jpg') as image:
    with image.clone() as flopped:
        flopped.flop()
        flopped.save(filename='transform-flopped.jpg')

The image transform-flopped.jpg generated by the above code looks like:

transform-flopped.jpg

Drawing

New in version 0.3.0.

The wand.drawing module provides some basic drawing functions. wand.drawing.Drawing object buffers instructions for drawing shapes into images, and then it can draw these shapes into zero or more images.

It’s also callable and takes an Image object:

from wand.drawing import Drawing
from wand.image import Image

with Drawing() as draw:
    # does something with ``draw`` object,
    # and then...
    with Image(filename='wandtests/assets/beach.jpg') as image:
        draw(image)

Arc

New in version 0.4.0.

Arcs can be drawn by using arc() method. You’ll need to define three pairs of (x, y) coordinates. First & second pair of coordinates will be the minimum bounding rectangle, and the last pair define the starting & ending degree.

An example:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.stroke_color = Color('black')
    draw.stroke_width = 2
    draw.fill_color = Color('white')
    draw.arc(( 25, 25),  # Stating point
             ( 75, 75),  # Ending point
             (135,-45))  # From bottom left around to top right
    with Image(width=100,
               height=100,
               background=Color('lightblue')) as img:
        draw.draw(img)
        img.save(filename='draw-arc.gif')
draw-arc.gif

Bezier

New in version 0.4.0.

You can draw bezier curves using bezier() method. This method requires at least four points to determine a bezier curve. Given as a list of (x, y) coordinates. The first & last pair of coordinates are treated as start & end, and the second & third pair of coordinates act as controls.

For example:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.stroke_color = Color('black')
    draw.stroke_width = 2
    draw.fill_color = Color('white')
    points = [(10,50),  # Start point
              (50,10),  # First control
              (50,90),  # Second control
              (90,50)]  # End point
    draw.bezier(points)
    with Image(width=100,
               height=100,
               background=Color('lightblue')) as image:
        draw(image)
draw-bezier.gif

Control width & color of curve with the drawing properties:

Circle

New in version 0.4.0.

You can draw circles using circle() method. Circles are drawn by defining two pairs of (x, y) coordinates. First coordinate for the center “origin” point, and a second pair for the outer perimeter. For example, the following code draws a circle in the middle of the image:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.stroke_color = Color('black')
    draw.stroke_width = 2
    draw.fill_color = Color('white')
    draw.circle((50, 50), # Center point
                (25, 25)) # Perimeter point
    with Image(width=100, height=100, background=Color('lightblue')) as image:
        draw(image)
draw-circle.gif

Color & Matte

New in version 0.4.0.

You can draw with colors directly on the coordinate system of an image. Define which color to set by setting fill_color. The behavior of color() is controlled by setting one of PAINT_METHOD_TYPES paint methods.

  • 'point' alters a single pixel.
  • 'replace' swaps on color for another. Threshold is influenced by fuzz.
  • 'floodfill' fills area of a color influenced by fuzz.
  • 'filltoborder' fills area of a color until border defined by border_color.
  • 'reset' replaces the whole image to a single color.

Example fill all to green boarder:

from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.border_color = Color('green')
    draw.fill_color = Color('blue')
    draw.color(15, 25, 'filltoborder')

The matte() method is identical to the color() method above, but alters the alpha channel of the color area selected. Colors can be manipulated, but not replaced.

with Drawing() as draw:
    draw.fill_color = None  # or Color('none')
    draw.matte(15, 25, 'floodfill')

Composite

New in version 0.4.0.

Similar to composite_channel(), this composite() method will render a given image on top of the drawing subject image following the COMPOSITE_OPERATORS options. An compositing image must be given with a destination top, left, width, and height values.

from wand.image import Image, COMPOSITE_OPERATORS
from wand.drawing import Drawing
from wand.display import display

wizard = Image(filename='wizard:')
rose = Image(filename='rose:')

for o in COMPOSITE_OPERATORS:
  w = wizard.clone()
  r = rose.clone()
  with Drawing() as draw:
    draw.composite(operator=o, left=175, top=250,
                   width=r.width, height=r.height, image=r)
    draw(w)
    display(w)

Ellipse

New in version 0.4.0.

Ellipse can be drawn by using the ellipse() method. Like drawing circles, the ellipse requires a origin point, however, a pair of (x, y) radius are used in relationship to the origin coordinate. By default a complete “closed” ellipse is drawn. To draw a partial ellipse, provide a pair of starting & ending degrees as the third parameter.

An example of a full ellipse:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.stroke_color = Color('black')
    draw.stroke_width = 2
    draw.fill_color = Color('white')
    draw.ellipse((50, 50), # Origin (center) point
                 (40, 20)) # 80px wide, and 40px tall
    with Image(width=100, height=100, background=Color('lightblue')) as image:
        draw(image)
draw-ellipse-full.gif

Same example as above, but with a half-partial ellipse defined by the third parameter:

draw.ellipse((50, 50), # Origin (center) point
             (40, 20), # 80px wide, and 40px tall
             (90,-90)) # Draw half of ellipse from bottom to top
draw-ellipse-part.gif

Lines

You can draw lines using line() method. It simply takes two (x, y) coordinates for start and end of a line. For example, the following code draws a diagonal line into the image:

draw.line((0, 0), image.size)
draw(image)

Or you can turn this diagonal line upside down:

draw.line((0, image.height), (image.width, 0))
draw(image)

The line color is determined by fill_color property, and you can change this of course. The following code draws a red diagonal line into the image:

from wand.color import Color

with Color('red') as color:
    draw.fill_color = color
    draw.line((0, 0), image.size)
    draw(image)

Paths

New in version 0.4.0.

Paths can be drawn by using any collection of path functions between path_start() and path_finish() methods. The available path functions are:

Each path method expects a destination point, and will draw from the current point to the new point. The destination point will become the new current point for the next applied path method. Destination points are given in the form of (x, y) coordinates to the to parameter, and can by relative or absolute to the current point by setting the relative flag. The path_curve() and path_curve_to_quadratic_bezier() expect additional control points, and can complement previous drawn curves by setting a smooth flag. When the smooth flag is set to True the first control point is assumed to be the reflection of the last defined control point.

For example:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.stroke_width = 2
    draw.stroke_color = Color('black')
    draw.fill_color = Color('white')
    draw.path_start()
    # Start middle-left
    draw.path_move(to=(10, 50))
    # Curve accross top-left to center
    draw.path_curve(to=(40, 0),
                    controls=[(10, -40), (30,-40)],
                    relative=True)
    # Continue curve accross bottom-right
    draw.path_curve(to=(40, 0),
                    controls=(30, 40),
                    smooth=True,
                    relative=True)
    # Line to top-right
    draw.path_vertical_line(10)
    # Diagonal line to bottom-left
    draw.path_line(to=(10, 90))
    # Close first & last points
    draw.path_close()
    draw.path_finish()
    with Image(width=100, height=100, background=Color('lightblue')) as image:
        draw(image)
draw-path.gif

Point

New in version 0.4.0.

You can draw points by using point() method. It simply takes two x, y arguments for the point coordinate.

The following example will draw points following a math function across a given image:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color
import math

with Drawing() as draw:
    for x in xrange(0, 100):
        y = math.tan(x) * 4
        draw.point(x, y + 50)
    with Image(width=100, height=100, background=Color('lightblue')) as image:
        draw(image)
draw-point-math.gif

Color of the point can be defined by setting the following property

Polygon

New in version 0.4.0.

Complex shapes can be created with the polygon() method. You can draw a polygon by given this method a list of points. Stroke line will automatically close between first & last point.

For example, the following code will draw a triangle into the image:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.stroke_width = 2
    draw.stroke_color = Color('black')
    draw.fill_color = Color('white')
    points = [(25, 25), (75, 50), (25, 75)]
    draw.polygon(points)
    with Image(width=100, height=100, background=Color('lightblue')) as image:
        draw(image)
draw-polygon.gif

Control the fill & stroke with the following properties:

Polyline

New in version 0.4.0.

Identical to polygon(), except polyline() will not close the stroke line between the first & last point.

For example, the following code will draw a two line path on the image:

from wand.image import Image
from wand.drawing import Drawing
from wand.color import Color

with Drawing() as draw:
    draw.stroke_width = 2
    draw.stroke_color = Color('black')
    draw.fill_color = Color('white')
    points = [(25, 25), (75, 50), (25, 75)]
    draw.polyline(points)
    with Image(width=100, height=100, background=Color('lightblue')) as image:
        draw(image)
draw-polyline.gif

Control the fill & stroke with the following properties:

Push & Pop

New in version 0.4.0.

When working with complex vector graphics, you can use ImageMagick’s internal graphic-context stack to manage different styles & operations. The methods push(), push_clip_path(), push_defs(), and push_pattern() are used to mark the beginning of a sub-routine. The clip path & pattern methods take a name based identifier argument, and can be referenced at a latter point with clip_path, or set_fill_pattern_url() / set_stroke_pattern_url() respectively. With stack management, pop() is used to mark the end of a sub-routine, and return the graphical context to its pervious state before push() was invoked. Methods pop_clip_path(), pop_defs(), and pop_pattern() exist to match there pop counterparts.

from wand.color import Color
from wand.image import Image
from wand.drawing import Drawing
from wand.compat import nested
from math import cos, pi, sin

with nested(Color('lightblue'),
            Color('transparent'),
            Drawing()) as (bg, fg, draw):
    draw.stroke_width = 3
    draw.fill_color = fg
    for degree in range(0, 360, 15):
        draw.push()  # Grow stack
        draw.stroke_color = Color('hsl({0}%, 100%, 50%)'.format(degree * 100 / 360))
        t = degree / 180.0 * pi
        x = 35 * cos(t) + 50
        y = 35 * sin(t) + 50
        draw.line((50, 50), (x, y))
        draw.pop()  # Restore stack
    with Image(width=100, height=100, background=Color('lightblue')) as img:
        draw(img)
_images/draw-push-pop.gif

Rectangles

New in version 0.3.6.

Changed in version 0.4.0.

If you want to draw rectangles use rectangle() method. It takes left/top coordinate, and right/bottom coordinate, or width and height. For example, the following code draws a square on the image:

draw.rectangle(left=10, top=10, right=40, bottom=40)
draw(image)

Or using width and height instead of right and bottom:

draw.rectangle(left=10, top=10, width=30, height=30)
draw(image)

Support for rounded corners was added in version 0.4.0. The radius argument sets corner rounding.

draw.rectangle(left=10, top=10, width=30, height=30, radius=5)
draw(image)

Both horizontal & vertical can be set independently with xradius & yradius respectively.

draw.rectangle(left=10, top=10, width=30, height=30, xradius=5, yradius=3)
draw(image)

Note that the stoke and the fill are determined by the following properties:

Texts

Drawing object can write texts as well using its text() method. It takes x and y coordinates to be drawn and a string to write:

draw.font = 'wandtests/assets/League_Gothic.otf'
draw.font_size = 40
draw.text(image.width / 2, image.height / 2, 'Hello, world!')
draw(image)

As the above code shows you can adjust several settings before writing texts:

Colorspace

Image types

Every Image object has type property which identifies its colorspace. The value can be one of IMAGE_TYPES enumeration, and set of its available values depends on its format as well. For example, 'grayscale' isn’t available on JPEG.

>>> from wand.image import Image
>>> with Image(filename='wandtests/assets/bilevel.gif') as img:
...     img.type
...
'bilevel'
>>> with Image(filename='wandtests/assets/sasha.jpg') as img2:
...    img2.type
...
'truecolor'

You can change this value:

with Image(filename='wandtests/assets/bilevel.gif') as img:
    img.type = 'truecolor'
    img.save(filename='truecolor.gif')

See also

-type — ImageMagick: command-line-Options
Corresponding command-line option of convert program.

Enable alpha channel

You can find whether an image has alpha channel and change it to have or not to have the alpha channel using alpha_channel property, which is preserving a bool value.

>>> with Image(filename='wandtests/assets/sasha.jpg') as img:
...    img.alpha_channel
...
False
>>> with Image(filename='wandtests/assets/croptest.png') as img:
...    img.alpha_channel
...
True

It’s a writable property:

with Image(filename='wandtests/assets/sasha.jpg') as img:
    img.alpha_channel = True

Color Enhancement

Evaluate Expression

New in version 0.4.1.

Pixel channels can be manipulated by applying a arithmetic, relational, or logical expression. See EVALUATE_OPS for a list of valid operations.

For example, when given image enhancement.jpg:

Chicago River

We can reduce the amount of data in the blue channel by applying the right-shift binary operator, and increase data in the right channel with left-shift operator:

from wand.image import Image

with Image(filename='enhancement.jpg') as img:
    # B >> 1
    img.evaluate(operator='rightshift', value=1, channel='blue')
    # R << 1
    img.evaluate(operator='leftshift', value=1, channel='red')
Chicago River - Evaluated right shift

Function Expression

New in version 0.4.1.

Similar to evaluate(), function() applies a multi-argument function to pixel channels. See FUNCTION_TYPES for a list of avalible function formulas.

For example, when given image enhancement.jpg:

Chicago River

We can apply a Sinusoid function with the following:

from wand.image import Image

with Image(filename='enhancement.jpg') as img:
    frequency = 3
    phase_shift = -90
    amplitude = 0.2
    bias = 0.7
    img.function('sinusoid', [frequency, phase_shift, amplitude, bias])
Chicago River - Sinusoid function

FX Expressions

New in version 0.4.1.

FX special effects are a powerful “micro” language to work with. Simple functions & operators offer a unique way to access & manipulate image data. The fx() method applies a FX expression, and generates a new Image instance.

For example, when given image enhancement.jpg:

Chicago River

We can create a custom DIY filter that will turn the image black & white, except colors with a hue between 195° & 252°:

from wand.image import Image

fx_filter='(hue > 0.55 && hue < 0.7) ? u : lightness'

with Image(filename='enhancement.jpg') as img:
     with img.fx(fx_filter) as filtered_img:
          filtered_img.save(filename='enhancement-fx.jpg')
Chicago River - FX Expressions

Gamma

New in version 0.4.1.

Gamma correction allows you to adjust the luminance of an image. Resulting pixels are defined as pixel^(1/gamma). The value of gamma is typically between 0.8 & 2.3 range, and value of 1.0 will not affect the resulting image.

The level() method can also adjust gamma value.

For example, when given image enhancement.jpg:

Chicago River

We can step through 4 pre-configured gamma correction values with the following:

from wand.image import Image

with Image(filename='enhancement.jpg') as img_src:
    for Y in [0.8, 0.9, 1.33, 1.66]:
        with Image(img_src) as img_cpy:
            img_cpy.gamma(Y)
Chicago River - Gamma Correction

Level

New in version 0.4.1.

Black & white boundaries of an image can be controlled with level() method. Similar to the gamma() method, mid-point levels can be adjusted with the gamma keyword argument.

The black and white point arguments are expecting values between 0.0 & 1.0 which represent percentages.

For example, when given image enhancement.jpg:

Chicago River

We can adjust the level range between 20% & 90% with slight mid-range increase:

from wand.image import Image

with Image(filename='enhancement.jpg') as img:
    img.level(0.2, 0.9, gamma=1.1)
    img.save(filename='enhancement-level.jpg')
Chicago River - Level Adjustment

Reading EXIF

New in version 0.3.0.

Image.metadata contains metadata of the image including EXIF. These are prefixed by 'exif:' e.g. 'exif:ExifVersion', 'exif:Flash'.

Here’s a straightforward example to access EXIF of an image:

exif = {}
with Image(filename='wandtests/assets/beach.jpg') as image:
    exif.update((k[5:], v) for k, v in image.metadata.items()
                           if k.startswith('exif:'))

Note

You can’t write into Image.metadata.

Sequence

Note

The image sequence-animation.gif used in this docs has been released into the public domain by its author, C6541 at Wikipedia project. This applies worldwide. (Source)

New in version 0.3.0.

Some images may actually consist of two or more images. For example, animated image/gif images consist of multiple frames. Some image/ico images have different sizes of icons.

sequence-animation.gif

For example, the above image sequence-animation.gif consists of the following frames (actually it has 60 frames, but we sample only few frames to show here):

frames of sequence-animation.gif

sequence is a Sequence

If we open this image, Image object has sequence. It’s a list-like object that maintain its all frames.

For example, len() for this returns the number of frames:

>>> from wand.image import Image
>>> with Image(filename='sequence-animation.gif') as image:
...     len(image.sequence)
...
60

You can get an item by index from sequence:

>>> with Image(filename='sequence-animation.gif') as image:
...     image.sequence[0]
...
<wand.sequence.SingleImage: ed84c1b (256x256)>

Or slice it:

>>> with Image(filename='sequence-animation.gif') as image:
...     image.sequence[5:10]
...
[<wand.sequence.SingleImage: 0f49491 (256x256)>,
 <wand.sequence.SingleImage: 8eba0a5 (256x256)>,
 <wand.sequence.SingleImage: 98c10fa (256x256)>,
 <wand.sequence.SingleImage: b893194 (256x256)>,
 <wand.sequence.SingleImage: 181ce21 (256x256)>]

Image versus SingleImage

Note that each item of sequence is a SingleImage instance, not Image.

Image is a container that directly represents image files like sequence-animation.gif, and SingleImage is a single image that represents frames in animations or sizes in image/ico files.

They both inherit BaseImage, the common abstract class. They share the most of available operations and properties like resize() and size, but some are not. For example, save() and mimetype are only provided by Image. delay and index are only available for SingleImage.

In most cases, images don’t have multiple images, so it’s okay if you think that Image and SingleImage are the same, but be careful when you deal with animated image/gif files or image/ico files that contain multiple icons.

Resource management

See also

wand.resource — Global resource management
There is the global resource to manage in MagickWand API. This module implements automatic global resource management through reference counting.

Objects Wand provides are resources to be managed. It has to be closed (destroyed) after using like file or database connection. You can deal with it using with very easily and explicitly:

with Image(filename='') as img:
    # deal with img...

Or you can call its destroy() (or close() if it is an Image instance) method manually:

try:
    img = Image(filename='')
    # deal with img...
finally:
    img.destroy()

Note

It also implements the destructor that invokes destroy(), and if your program runs on CPython (which does reference counting instead of ordinary garbage collection) most of resources are automatically deallocated.

However it’s just depending on CPython’s implementation detail of memory management, so it’s not a good idea. If your program runs on PyPy (which implements garbage collector) for example, invocation time of destructors is not determined, so the program would be broken.

Running tests

Wand has unit tests and regression tests. It can be run using setup.py script:

$ python setup.py test

It uses pytest as its testing library. The above command will automatically install pytest as well if it’s not installed yet.

Or you can manually install pytest and then use py.test command. It provides more options:

$ pip install pytest
$ py.test

Skipping tests

There are some time-consuming tests. You can skip these tests using --skip-slow option:

$ py.test --skip-slow

You can run only tests you want using -k option.

$ py.test -k image

Using tox

Wand should be compatible with various Python implementations including CPython 2.6, 2.7, PyPy. tox is a testing software that helps Python packages to test on various Python implementations at a time.

It can be installed using pip:

$ pip install tox

If you type just tox at Wand directory it will be tested on multiple Python interpreters:

$ tox
GLOB sdist-make: /Users/emcconville/Desktop/wand/setup.py
py26 create: /Users/emcconville/Desktop/wand/.tox/py26
py26 installdeps: pytest
py26 sdist-inst: /Users/emcconville/Desktop/wand/.tox/dist/Wand-0.2.2.zip
py26 runtests: commands[0]
...

You can use a double -- to pass options to pytest:

$ tox -- -k sequence

Continuous Integration

Build Status

Travis CI automatically builds and tests every commit and pull request. The above banner image shows the current status of Wand build. You can see the detail of the current status from the following URL:

https://travis-ci.org/emcconville/wand

Code Coverage

Coverage Status

Coveralls support tracking Wand’s test coverage. The above banner image shows the current status of Wand coverage. You can see the details of the current status from the following URL:

https://coveralls.io/r/emcconville/wand

Roadmap

Version 0.5

Image layers (#22)

Wand 0.5 will be able to deal with layers of an image.

Its branch name will be layer.

Very future versions

CFFI
Wand 0.5 will move to CFFI from ctypes.
PIL compatibility layer

PIL has very long history and the most of Python projects still depend on it. We will work on PIL compatibility layer using Wand. It will provide two ways to emulate PIL:

  • Module-level compatibility which can be used by changing import:

    try:
        from wand.pilcompat import Image
    except ImportError:
        from PIL import Image
    
  • Global monkeypatcher which changes sys.modules:

    from wand.pilcompat.monkey import patch; patch()
    import PIL.Image  # it imports wand.pilcompat.Image module
    
CLI (covert command) to Wand compiler (#100)

Primary interface of ImageMagick is convert command. It provides a small parameter language, and many answers on the Web contain code using this. The problem is that you can’t simply copy-and-paste these code to utilize Wand.

This feature is to make these CLI codes possible to be used with Wand.

Supporting __array_interface__() for NumPy (#65)

It makes numpy.asarray() able to take Image object to deal with its pixels as matrix.

Its branch name will be numpy.

Wand Changelog

0.4 series

Version 0.4.5

To be released.

  • Improve library searching when MAGICK_HOME environment variable is set. [#320 by Chase Anderson]
  • Fixed misleading TypeError: object of type ‘NoneType’ has no len() during destroy routines. [#346 by Carey Metcalfe]
  • Added Image.blur() method (MagickBlurImage()). [#311 by Alexander Karpinsky]
  • Added Image.extent() method (MagickExtentImage()). [#233 by Jae-Myoung Yu]
  • Added Image.resample() method (MagickResampleImage()). [#244 by Zio Tibia]
Version 0.4.4

Released on October 22, 2016.

Version 0.4.3

Released on June 1, 2016.

Version 0.4.2

Released on November 30, 2015.

  • Fixed ImportError on MSYS2. [#257 by Eon Jeong]
  • Added Image.quantize() method (MagickQuantizeImage()). [#152 by Kang Hyojun, #262 by Jeong YunWon]
  • Added Image.transform_colorspace() quantize (MagickTransformImageColorspace()). [#152 by Adrian Jung, #262 by Jeong YunWon]
  • Now ImageMagick DLL can be loaded on Windows even if its location is stored in the resitry. [#261 by Roeland Schoukens]
  • Added depth parameter to Image constructor. The depth, width and height parameters can be used with the filename, file and blob parameters to load raw pixel data. [#261 by Roeland Schoukens]
Version 0.4.1

Released on August 3, 2015.

Version 0.4.0

Released on February 20, 2015.

See also

What’s new in Wand 0.4?
This guide introduces what’s new in Wand 0.4.

0.3 series

Version 0.3.9

Released on December 20, 2014.

  • Added 'pdf:use-cropbox' option to Image.options dictionary (and OPTIONS constant). [#185 by Christoph Neuroth]
  • Fixed a bug that exception message was bytes instead of str on Python 3.
  • The size parameter of Font class becomes optional. Its default value is 0, which means autosized. [#191 by Cha, Hojeong]
  • Fixed a bug that Image.read() had tried using MagickReadImageFile() even when the given file object has no mode attribute. [#205 by Stephen J. Fuhry]
Version 0.3.8

Released on August 3, 2014.

  • Fixed a bug that transparent background becomes filled with white when SVG is converted to other bitmap image format like PNG. [#184]
  • Added Image.negate() method. [#174 by Park Joon-Kyu]
  • Fixed a segmentation fault on Image.modulate() method. [#173 by Ted Fung, #158]
  • Added suggestion to install freetype also if Homebrew is used. [#141]
  • Now image/x-gif also is determined as animation. [#181 by Juan-Pablo Scaletti]
Version 0.3.7

Released on March 25, 2014.

  • A hotfix of debug prints made at 0.3.6.
Version 0.3.6

Released on March 23, 2014.

Version 0.3.5

Released on September 13, 2013.

  • Fix segmentation fault on Image.save() method. [#150]
Version 0.3.4

Released on September 9, 2013.

  • Added Image.modulate() method. [#134 by Dan P. Smith]
  • Added Image.colorspace property. [#135 by Volodymyr Kuznetsov]
  • Added Image.unsharp_mask() method. [#136 by Volodymyr Kuznetsov]
  • Added 'jpeg:sampling-factor' option to Image.options dictionary (and OPTIONS constant). [#137 by Volodymyr Kuznetsov]
  • Fixed ImageMagick shared library resolution on Arch Linux. [#139, #140 by Sergey Tereschenko]
  • Added Image.sample() method. [#142 by Michael Allen]
  • Fixed a bug that Image.save() preserves only one frame of the given animation when file-like object is passed. [#143, #145 by Michael Allen]
  • Fixed searching of ImageMagick shared library with HDR support enabled. [#148, #149 by Lipin Dmitriy]
Version 0.3.3

Released on August 4, 2013. It’s author’s birthday.

Version 0.3.2

Released on July 11, 2013.

  • Fixed incorrect encoding of filenames. [#122]
  • Fixed key type of Image.metadata dictionary to str from bytes in Python 3.
  • Fixed CentOS compatibility [#116, #124 by Pierre Vanliefland]
    • Made DrawSetTextInterlineSpacing() and DrawGetTextInterlineSpacing() optional.
    • Added exception in drawing API when trying to use DrawSetTextInterlineSpacing() and DrawGetTextInterlineSpacing() functions when they are not available.
    • Added WandLibraryVersionError class for library versions issues.
Version 0.3.1

Released on June 23, 2013.

  • Fixed ImportError on Windows.
Version 0.3.0

Released on June 17, 2013.

See also

What’s new in Wand 0.3?
This guide introduces what’s new in Wand 0.3.

0.2 series

Version 0.2.4

Released on May 28, 2013.

  • Fix NameError in Resource.resource setter. [#89 forwareded from Debian bug report #699064 by Jakub Wilk]
  • Fix the problem of library loading for Mac with Homebrew and Arch Linux. [#102 by Roel Gerrits, #44]
Version 0.2.3

Released on January 25, 2013.

  • Fixed a bug that Image.transparentize() method (and Image.watermark() method which internally uses it) didn’t work.
  • Fixed segmentation fault occurred when Color.red, Color.green, or Color.blue is accessed.
  • Added Color.alpha property.
  • Fixed a bug that format converting using Image.format property or Image.convert() method doesn’t correctly work to save blob.
Version 0.2.2

Released on September 24, 2012.

  • A compatibility fix for FreeBSD. [Patch by Olivier Duchateau]
  • Now Image can be instantiated without any opening. Instead, it can take width/height and background. [#53 by Michael Elovskikh]
  • Added Image.transform() method which is a convenience method accepting geometry strings to perform cropping and resizing. [#50 by Mitch Lindgren]
  • Added Image.units property. [#45 by Piotr Florczyk]
  • Now Image.resize() method raises a proper error when it fails for any reason. [#41 by Piotr Florczyk]
  • Added Image.type property. [#33 by Yauhen Yakimovich, #42 by Piotr Florczyk]
Version 0.2.1

Released on August 19, 2012. Beta version.

Version 0.2.0

Released on June 20, 2012. Alpha version.

  • Added Image.transparentize() method. [#19 by Jeremy Axmacher]
  • Added Image.composite() method. [#19 by Jeremy Axmacher]
  • Added Image.watermark() method. [#19 by Jeremy Axmacher]
  • Added Image.quantum_range property. [#19 by Jeremy Axmacher]
  • Added Image.reset_coords() method and reset_coords option to Image.rotate() method. [#20 by Juan Pablo Scaletti]
  • Added Image.strip() method. [#23 by Dmitry Vukolov]
  • Added Image.compression_quality property. [#23 by Dmitry Vukolov]
  • Now the current version can be found from the command line interface: python -m wand.version.

0.1 series

Version 0.1.10

Released on May 8, 2012. Still alpha version.

  • So many Windows compatibility issues are fixed. [#14 by John Simon]
  • Added wand.api.libmagick.
  • Fixed a bug that raises AttributeError when it’s trying to warn. [#16 by Tim Dettrick]
  • Now it throws ImportError instead of AttributeError when the shared library fails to load. [#17 by Kieran Spear]
  • Fixed the example usage on index page of the documentation. [#18 by Jeremy Axmacher]
Version 0.1.9

Released on December 23, 2011. Still alpha version.

Version 0.1.8

Released on December 2, 2011. Still alpha version.

Version 0.1.7

Released on November 10, 2011. Still alpha version.

  • Added Image.mimetype property.
  • Added Image.crop() method for in-place crop.
Version 0.1.6

Released on October 31, 2011. Still alpha version.

  • Removed a side effect of Image.make_blob() method that changes the image format silently.
  • Added Image.format property.
  • Added Image.convert() method.
  • Fixed a bug about Python 2.6 compatibility.
  • Use the internal representation of PixelWand instead of the string representaion for Color type.
Version 0.1.5

Released on October 28, 2011. Slightly mature alpha version.

  • Now Image can read Python file objects by file keyword argument.
  • Now Image.save() method can write into Python file objects by file keyword argument.
  • Image.make_blob()’s format argument becomes omittable.
Version 0.1.4

Released on October 27, 2011. Hotfix of the malformed Python package.

Version 0.1.3

Released on October 27, 2011. Slightly mature alpha version.

  • Pixel getter for Image.
  • Row getter for Image.
  • Mac compatibility.
  • Windows compatibility.
  • 64-bit processor compatibility.
Version 0.1.2

Released on October 16, 2011. Still alpha version.

Version 0.1.1

Released on October 4, 2011. Still alpha version.

Version 0.1.0

Released on October 1, 2011. Very alpha version.

Talks and Presentations

References

wand — Simple MagickWand API binding for Python

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 = {'all_channels': 134217727, 'alpha': 8, 'black': 32, 'blue': 4, 'composite_channels': 47, 'cyan': 1, 'default_channels': 134217719, 'gray': 1, 'gray_channels': 128, 'green': 2, 'index': 32, 'magenta': 2, 'opacity': 8, 'red': 1, 'rgb_channels': 128, 'sync_channels': 256, 'true_alpha': 64, 'undefined': 0, 'yellow': 4}

(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.COLORSPACE_TYPES = ('undefined', 'rgb', 'gray', 'transparent', 'ohta', 'lab', 'xyz', 'ycbcr', 'ycc', 'yiq', 'ypbpr', 'yuv', 'cmyk', 'srgb', 'hsb', 'hsl', 'hwb', 'rec601luma', 'rec601ycbcr', 'rec709luma', 'rec709ycbcr', 'log', 'cmy', 'luv', 'hcl', 'lch', 'lms', 'lchab', 'lchuv', 'scrgb', 'hsi', 'hsv', 'hclp', 'ydbdr')

(tuple) The list of colorspaces.

  • 'undefined'
  • 'rgb'
  • 'gray'
  • 'transparent'
  • 'ohta'
  • 'lab'
  • 'xyz'
  • 'ycbcr'
  • 'ycc'
  • 'yiq'
  • 'ypbpr'
  • 'yuv'
  • 'cmyk'
  • 'srgb'
  • 'hsb'
  • 'hsl'
  • 'hwb'
  • 'rec601luma'
  • 'rec601ycbcr'
  • 'rec709luma'
  • 'rec709ycbcr'
  • 'log'
  • 'cmy'
  • 'luv'
  • 'hcl'
  • 'lch'
  • 'lms'
  • 'lchab'
  • 'lchuv'
  • 'scrgb'
  • 'hsi'
  • 'hsv'
  • 'hclp'
  • 'ydbdr'

See also

ImageMagick Color Management
Describes the ImageMagick color management operations

New in version 0.3.4.

wand.image.COMPARE_METRICS = ('undefined', 'absolute', 'mean_absolute', 'mean_error_per_pixel', 'mean_squared', 'normalized_cross_correlation', 'peak_absolute', 'peak_signal_to_noise_ratio', 'perceptual_hash', 'root_mean_square')

(tuple) The list of compare metric types

  • 'undefined'
  • 'absolute'
  • 'mean_absolute'
  • 'mean_error_per_pixel'
  • 'mean_squared'
  • 'normalized_cross_correlation'
  • 'peak_absolute'
  • 'peak_signal_to_noise_ratio'
  • 'perceptual_hash'
  • 'root_mean_square'

New in version 0.4.3.

wand.image.COMPOSITE_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')

(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'

Changed in version 0.3.0: Renamed from COMPOSITE_OPS to COMPOSITE_OPERATORS.

See also

Compositing Images ImageMagick v6 Examples
Image composition is the technique of combining images that have, or do not have, transparency or an alpha channel. This is usually performed using the IM composite command. It may also be performed as either part of a larger sequence of operations or internally by other image operators.
ImageMagick Composition Operators
Demonstrates the results of applying the various composition composition operators.
wand.image.COMPRESSION_TYPES = ('undefined', 'b44a', 'b44', 'bzip', 'dxt1', 'dxt3', 'dxt5', 'fax', 'group4', 'jbig1', 'jbig2', 'jpeg2000', 'jpeg', 'losslessjpeg', 'lzma', 'lzw', 'no', 'piz', 'pxr24', 'rle', 'zip', 'zips')

(tuple) The list of Image.compression types.

New in version 0.3.6.

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', 'rootmeansquare')

(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.GRAVITY_TYPES = ('forget', 'north_west', 'north', 'north_east', 'west', 'center', 'east', 'south_west', 'south', 'south_east', 'static')

(tuple) The list of gravity types.

New in version 0.3.0.

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.ORIENTATION_TYPES = ('undefined', 'top_left', 'top_right', 'bottom_right', 'bottom_left', 'left_top', 'right_top', 'right_bottom', 'left_bottom')

(tuple) The list of orientation types.

New in version 0.3.0.

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
wand.image.FUNCTION_TYPES = ('undefined', 'polynomial', 'sinusoid', 'arcsin', 'arctan')

(tuple) The list of Image.function types.

  • 'undefined'
  • 'polynomial'
  • 'sinusoid'
  • 'arcsin'
  • 'arctan'
class wand.image.BaseImage(wand)

The abstract base of Image (container) and SingleImage. That means the most of operations, defined in this abstract classs, are possible for both Image and SingleImage.

New in version 0.3.0.

alpha_channel

(bool) Get state of image alpha channel. It can also be used to enable/disable alpha channel, but with different behavior new, copied, or existing.

Behavior of setting alpha_channel is defined with the following values:

  • 'activate', 'on', or True will enable an images
    alpha channel. Existing alpha data is preserved.
  • 'deactivate', 'off', or False will disable an images
    alpha channel. Any data on the alpha will be preserved.
  • 'associate' & 'disassociate' toggle alpha channel flag in
    certain image-file specifications.
  • 'set' enables and resets any data in an images alpha channel.
  • 'opaque' enables alpha/matte channel, and forces full opaque
    image.
  • 'transparent' enables alpha/matte channel, and forces full
    transparent image.
  • 'extract' copies data in alpha channel across all other channels,
    and disables alpha channel.
  • 'copy' calculates the gray-scale of RGB channels,
    and applies it to alpha channel.
  • 'shape' is identical to 'copy', but will color the resulting
    image with the value defined with background_color.
  • 'remove' will composite background_color value.
  • 'background' replaces full-transparent color with background
    color.

New in version 0.2.1.

Changed in version 0.4.1: Support for additional setting values. However Image.alpha_channel will continue to return bool if the current alpha/matte state is enabled.

animation

(bool) Whether the image is animation or not. It doesn’t only mean that the image has two or more images (frames), but all frames are even the same size. It’s about image format, not content. It’s False even if image/ico consits of two or more images of the same size.

For example, it’s False for image/jpeg, image/gif, image/ico.

If image/gif has two or more frames, it’s True. If image/gif has only one frame, it’s False.

New in version 0.3.0.

Changed in version 0.3.8: Became to accept image/x-gif as well.

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.

blur(*args, **kwargs)

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

Parameters:
  • radius (numbers.Real) – the radius of the, in pixels, not counting the center pixel
  • sigma (numbers.Real) – the standard deviation of the, in pixels

New in version 0.4.5.

caption(*args, **kwargs)

Writes a caption text into the position.

Parameters:

New in version 0.3.0.

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.

colorspace

(basestring) The image colorspace.

Defines image colorspace as in COLORSPACE_TYPES enumeration.

It may raise ValueError when the colorspace is unknown.

New in version 0.3.4.

compare(image, metric='undefined')

Compares an image to a reconstructed image.

Parameters:
  • image (wand.image.Image) – The reference image
  • metric (basestring) – The metric type to use for comparing.
Returns:

The difference image(wand.image.Image), the computed distortion between the images (numbers.Integral)

Return type:

tuple

..versionadded:: 0.4.3

composite(*args, **kwargs)

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.

composite_channel(*args, **kwargs)

Composite two images using the particular channel.

Parameters:
  • channel – the channel type. available values can be found in the CHANNELS mapping
  • image (Image) – the composited source image. (the receiver image becomes the destination)
  • operator – the operator that affects how the composite is applied to the image. available values can be found in the COMPOSITE_OPERATORS list
  • left (numbers.Integral) – the column offset of the composited source image
  • top (numbers.Integral) – the row offset of the composited source image
Raises:

ValueError – when the given channel or operator is invalid

New in version 0.3.0.

compression_quality

(numbers.Integral) Compression quality of this image.

New in version 0.2.0.

crop(*args, **kwargs)

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.
  • gravity (GRAVITY_TYPES) – optional flag. If set, will calculate the top and left attributes. This requires both width and height parameters to be included.
Raises:

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.4.1: Added gravity option. Using gravity along with width & height to auto-adjust left & top attributes.

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.

dirty = None

(bool) Whether the image is changed or not.

distort(*args, **kwargs)

Distorts an image using various distorting methods.

Parameters:
  • method (basestring) – Distortion method name from DISTORTION_METHODS
  • arguments (collections.Sequence) – List of distorting float arguments unique to distortion method
  • best_fit (bool) – Attempt to resize resulting image fit distortion. Defaults False

New in version 0.4.1.

equalize(*args, **kwargs)

Equalizes the image histogram

New in version 0.3.10.

evaluate(*args, **kwargs)

Apply arithmetic, relational, or logical expression to an image.

Percent values must be calculated against the quantum range of the image:

fifty_percent = img.quantum_range * 0.5
img.evaluate(operator='set', value=fifty_percent)
Parameters:
  • operator (EVALUATE_OPS) – Type of operation to calculate
  • value (numbers.Real) – Number to calculate with operator
  • channel (CHANNELS) – Optional channel to apply operation on.
Raises:
  • TypeError – When value is not numeric.
  • ValueError – When operator, or channel are not defined in constants.

New in version 0.4.1.

extent(*args, **kwargs)

extends the image as defined by the geometry, gravity, and wand background color. Set the (x,y) offset of the geometry to move the original wand relative to the extended wand.

Parameters:

New in version 0.4.5.

flip(*args, **kwargs)

Creates a vertical mirror image by reflecting the pixels around the central x-axis. It manipulates the image in place.

New in version 0.3.0.

flop(*args, **kwargs)

Creates a horizontal mirror image by reflecting the pixels around the central y-axis. It manipulates the image in place.

New in version 0.3.0.

font

(wand.font.Font) The current font options.

font_path

(basestring) The path of the current font. It also can be set.

font_size

(numbers.Real) The font size. It also can be set.

frame(*args, **kwargs)

Creates a bordered frame around image. Inner & outer bevel can simulate a 3D effect.

Parameters:

New in version 0.4.1.

function(*args, **kwargs)

Apply an arithmetic, relational, or logical expression to an image.

Defaults entire image, but can isolate affects to single color channel by passing CHANNELS value to channel parameter.

Note

Support for function methods added in the following versions of ImageMagick.

  • 'polynomial' >= 6.4.8-8
  • 'sinusoid' >= 6.4.8-8
  • 'arcsin' >= 6.5.3-1
  • 'arctan' >= 6.5.3-1
Parameters:
  • function (basestring) – a string listed in FUNCTION_TYPES
  • arguments (collections.Sequence) – a sequence of doubles to apply against function
  • channel (basestring) – optional CHANNELS, defaults all
Raises:
  • ValueError – when a function, or channel is not defined in there respected constant
  • TypeError – if arguments is not a sequence

New in version 0.4.1.

fx(*args, **kwargs)

Manipulate each pixel of an image by given expression.

FX will preserver current wand instance, and return a new instance of Image containing affected pixels.

Defaults entire image, but can isolate affects to single color channel by passing CHANNELS value to channel parameter.

See also

The anatomy of FX expressions can be found at http://www.imagemagick.org/script/fx.php

Parameters:
  • expression (basestring) – The entire FX expression to apply
  • channel (CHANNELS) – Optional channel to target.
Returns:

A new instance of an image with expression applied

Return type:

Image

New in version 0.4.1.

gaussian_blur(*args, **kwargs)

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

Parameters:
  • radius (numbers.Real) – the radius of the, in pixels, not counting the center pixel
  • sigma (numbers.Real) – the standard deviation of the, in pixels

New in version 0.3.3.

gravity

(basestring) The text placement gravity used when annotating with text. It’s a string from GRAVITY_TYPES list. It also can be set.

height

(numbers.Integral) The height of this image.

histogram

(HistogramDict) The mapping that represents the histogram. Keys are Color objects, and values are the number of pixels.

New in version 0.3.0.

liquid_rescale(*args, **kwargs)

Rescales the image with seam carving, also known as image retargeting, content-aware resizing, or liquid rescaling.

Parameters:
  • width (numbers.Integral) – the width in the scaled image
  • height (numbers.Integral) – the height in the scaled image
  • delta_x (numbers.Real) – maximum seam transversal step. 0 means straight seams. default is 0
  • rigidity (numbers.Real) – introduce a bias for non-straight seams. default is 0
Raises:

wand.exceptions.MissingDelegateError – when ImageMagick isn’t configured --with-lqr option.

Note

This feature requires ImageMagick to be configured --with-lqr option. Or it will raise MissingDelegateError:

See also

Seam carving — Wikipedia
The article which explains what seam carving is on Wikipedia.
matte_color

(wand.color.Color) The color value of the matte channel. This can also be set.

..versionadded:: 0.4.1

merge_layers(*args, **kwargs)

Composes all the image layers from the current given image onward to produce a single image of the merged layers.

The inital canvas’s size depends on the given ImageLayerMethod, and is initialized using the first images background color. The images are then compositied onto that image in sequence using the given composition that has been assigned to each individual image. The method must be set with a value from IMAGE_LAYER_METHOD that is acceptable to this operation. (See ImageMagick documentation for more details.)

Parameters:method (basestring) – the method of selecting the size of the initial canvas.

New in version 0.4.3.

modulate(*args, **kwargs)

Changes the brightness, saturation and hue of an image. We modulate the image with the given brightness, saturation and hue.

Parameters:
Raises:

ValueError – when one or more arguments are invalid

New in version 0.3.4.

negate(grayscale=False, channel=None)

Negate the colors in the reference image.

Parameters:
  • grayscale (bool) – if set, only negate grayscale pixels in the image.
  • channel (basestring) – the channel type. available values can be found in the CHANNELS mapping. If None, negate all channels.

New in version 0.3.8.

options = None

(OptionDict) The mapping of internal option settings.

New in version 0.3.0.

Changed in version 0.3.4: Added 'jpeg:sampling-factor' option.

Changed in version 0.3.9: Added 'pdf:use-cropbox' option.

orientation

(basestring) The image orientation. It’s a string from ORIENTATION_TYPES list. It also can be set.

New in version 0.3.0.

page

The dimensions and offset of this Wand’s page as a 4-tuple: (width, height, x, y).

Note that since it is based on the virtual canvas, it may not equal the dimensions of an image. See the ImageMagick documentation on the virtual canvas for more information.

New in version 0.4.3.

page_height

(numbers.Integral) The height of the page for this wand.

New in version 0.4.3.

page_width

(numbers.Integral) The width of the page for this wand.

New in version 0.4.3.

page_x

(numbers.Integral) The X-offset of the page for this wand.

New in version 0.4.3.

page_y

(numbers.Integral) The Y-offset of the page for this wand.

New in version 0.4.3.

quantize(*args, **kwargs)

quantize analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

Parameters:
  • number_colors (numbers.Integral) – the number of colors.
  • colorspace_type (basestring) – colorspace_type. available value can be found in the COLORSPACE_TYPES
  • treedepth (numbers.Integral) – normally, this integer value is zero or one. a zero or one tells quantize() to choose a optimal tree depth of log4(number_colors). a tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. in some cases, such as an image with low color dispersion (a few number of colors), a value other than log4(number_colors) is required. to expand the color tree completely, use a value of 8
  • dither (bool) – a value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve
  • measure_error (bool) – a value other than zero measures the difference between the original and quantized images. this difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value

New in version 0.4.2.

quantum_range

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

New in version 0.2.0.

resample(*args, **kwargs)

Adjust the number of pixels in an image so that when displayed at the given Resolution or Density the image will still look the same size in real world terms.

Parameters:
  • x_res (numbers.Real) – the X resolution (density) in the scaled image. default is the original resolution.
  • y_res (numbers.Real) – the Y resolution (density) in the scaled image. default is the original resolution.
  • 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

New in version 0.4.5.

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(*args, **kwargs)

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.

resolution

(tuple) Resolution of this image.

New in version 0.3.0.

rotate(*args, **kwargs)

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.

sample(*args, **kwargs)

Resizes the image by sampling the pixels. It’s basically quicker than resize() except less quality as a tradeoff.

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

New in version 0.3.4.

sequence = None

(collections.Sequence) The list of SingleImages that the image contains.

New in version 0.3.0.

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

threshold(*args, **kwargs)

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. It manipulates the image in place.

Parameters:
  • threshold (numbers.Real) – threshold as a factor of quantum
  • channel (basestring) – the channel type. available values can be found in the CHANNELS mapping. If None, threshold all channels.

New in version 0.3.10.

transform(*args, **kwargs)

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

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.

transform_colorspace(*args, **kwargs)

Transform image’s colorspace.

Parameters:colorspace_type (basestring) – colorspace_type. available value can be found in the COLORSPACE_TYPES

New in version 0.4.2.

transparent_color(*args, **kwargs)

Makes the color color a transparent color with a tolerance of fuzz. The alpha parameter specify the transparency level and the parameter fuzz specify the tolerance.

Parameters:
  • color (wand.color.Color) – The color that should be made transparent on the image, color object
  • alpha (numbers.Real) – the level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.
  • fuzz (numbers.Integral) – By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the color.
  • invert (bool) – Boolean to tell to paint the inverse selection.

New in version 0.3.0.

transparentize(*args, **kwargs)

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.

type

(basestring) The image type.

Defines image type as in 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.

unsharp_mask(*args, **kwargs)

Sharpens the image using unsharp mask filter. 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.

Parameters:
  • radius (numbers.Real) – the radius of the Gaussian, in pixels, not counting the center pixel
  • sigma (numbers.Real) – the standard deviation of the Gaussian, in pixels
  • amount (numbers.Real) – the percentage of the difference between the original and the blur image that is added back into the original
  • threshold (numbers.Real) – the threshold in pixels needed to apply the diffence amount

New in version 0.3.4.

virtual_pixel

(basestring) The virtual pixel of image. This can also be set with a value from VIRTUAL_PIXEL_METHOD … versionadded:: 0.4.1

wand

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

watermark(*args, **kwargs)

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.ChannelDepthDict(image)

The mapping table of channels to their depth.

Parameters:image (Image) – an image instance

Note

You don’t have to use this by yourself. Use Image.channel_depths property instead.

New in version 0.3.0.

class wand.image.ChannelImageDict(image)

The mapping table of separated images of the particular channel from the image.

Parameters:image (Image) – an image instance

Note

You don’t have to use this by yourself. Use Image.channel_images property instead.

New in version 0.3.0.

exception wand.image.ClosedImageError

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

class wand.image.HistogramDict(image)

Specialized mapping object to represent color histogram. Keys are colors, and values are the number of pixels.

Parameters:image (BaseImage) – the image to get its histogram

New in version 0.3.0.

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

An image object.

Parameters:
  • image (Image) – makes an exact copy of the image
  • blob (bytes) – 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 or an image loaded from raw data.
  • height (numbers.Integral) – the height of new blank imgage or an image loaded from raw data.
  • depth (numbers.Integral) – the depth used when loading raw data.
  • background (wand.color.Color) – an optional background color. default is transparent
  • resolution (collections.Sequence, numbers.Integral) – set a resolution value (dpi), useful for vectorial formats (like pdf)

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.

New in version 0.3.0: The resolution parameter.

New in version 0.4.2: The depth parameter.

Changed in version 0.4.2: The depth, width and height parameters can be used with the filename, file and blob parameters to load raw pixel data.

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

auto_orient(*args, **kwargs)

Adjusts an image so that its orientation is suitable for viewing (i.e. top-left orientation). If available it uses MagickAutoOrientImage() (was added in ImageMagick 6.8.9+) if you have an older magick library, it will use _auto_orient() method for fallback.

New in version 0.4.1.

blank(width, height, background=None)

Creates blank image.

Parameters:
Returns:

blank image

Return type:

Image

New in version 0.3.0.

border(color, width, height)

Surrounds the image with a border.

Parameters:

New in version 0.3.0.

channel_depths = None

(ChannelDepthDict) The mapping of channels to their depth. Read only.

New in version 0.3.0.

channel_images = None

(ChannelImageDict) The mapping of separated channels from the image.

with image.channel_images['red'] as red_image:
    display(red_image)
clear()

Clears resources associated with the image, leaving the image blank, and ready to be used with new image.

New in version 0.3.0.

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.

compression

(basestring) The type of image compression. It’s a string from COMPRESSION_TYPES list. It also can be set.

New in version 0.3.6.

contrast_stretch(*args, **kwargs)

Enhance contrast of image by adjusting the span of the available colors.

If only black_point is given, match the CLI behavior by assuming the white_point has the same delta percentage off the top e.g. contrast stretch of 15% is calculated as black_point = 0.15 and white_point = 0.85.

Parameters:
  • black_point (numbers.Real) – black point between 0.0 and 1.0. default is 0.0
  • white_point (numbers.Real) – white point between 0.0 and 1.0. default value of 1.0 minus black_point
  • channel (CHANNELS) – optional color channel to apply contrast stretch
Raises:

ValueError – if channel is not in CHANNELS

New in version 0.4.1.

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.

destroy()

Manually remove SingleImage’s in the Sequence, allowing it to be properly garbage collected after using a with Image() context manager.

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.

gamma(*args, **kwargs)

Gamma correct image.

Specific color channels can be correct individual. Typical values range between 0.8 and 2.3.

Parameters:
  • adjustment_value (numbers.Real) – value to adjust gamma level
  • channel (basestring) – optional channel to apply gamma correction
Raises:

New in version 0.4.1.

level(black=0.0, white=None, gamma=1.0, channel=None)

Adjusts the levels of an image by scaling the colors falling between specified black and white points to the full available quantum range.

If only black is given, white will be adjusted inward.

Parameters:
  • black (numbers.Real) – Black point, as a percentage of the system’s quantum range. Defaults to 0.
  • white (numbers.Real) – White point, as a percentage of the system’s quantum range. Defaults to 1.0.
  • gamma (numbers.Real) – Optional gamma adjustment. Values > 1.0 lighten the image’s midtones while values < 1.0 darken them.
  • channel (CHANNELS) – The channel type. Available values can be found in the CHANNELS mapping. If None, normalize all channels.

New in version 0.4.1.

linear_stretch(*args, **kwargs)

Enhance saturation intensity of an image.

Parameters:
  • black_point (numbers.Real) – Black point between 0.0 and 1.0. Default 0.0
  • white_point (numbers.Real) – White point between 0.0 and 1.0. Default 1.0

New in version 0.4.1.

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:bytes
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.

metadata = None

(Metadata) The metadata mapping of the image. Read only.

New in version 0.3.0.

mimetype

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

New in version 0.1.7.

normalize(channel=None)

Normalize color channels.

Parameters:channel (basestring) – the channel type. available values can be found in the CHANNELS mapping. If None, normalize all channels.
read(file=None, filename=None, blob=None, resolution=None)

Read new image into Image() object.

Parameters:
  • blob (bytes) – reads an image from the blob byte array
  • file (file object) – reads an image from the file object
  • filename (basestring) – reads an image from the filename string
  • resolution (collections.Sequence, numbers.Integral) – set a resolution value (DPI), useful for vectorial formats (like PDF)

New in version 0.3.0.

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 (basestring) – a filename string to write to

New in version 0.1.5: The file parameter.

New in version 0.1.1.

strip()

Strips an image of all profiles and comments.

New in version 0.2.0.

transpose(*args, **kwargs)

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

New in version 0.4.1.

transverse(*args, **kwargs)

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

New in version 0.4.1.

trim(color=None, fuzz=0)

Remove solid border from image. Uses top left pixel as a guide by default, or you can also specify the color to remove.

Parameters:
  • color (Color) – the border color to remove. if it’s omitted top left pixel is used by default
  • fuzz (numbers.Integral) – Defines how much tolerance is acceptable to consider two colors as the same.

New in version 0.3.0: Optional color and fuzz parameters.

New in version 0.2.1.

class wand.image.ImageProperty(image)

The mixin class to maintain a weak reference to the parent Image object.

New in version 0.3.0.

image

(Image) The parent image.

It ensures that the parent Image, which is held in a weak reference, still exists. Returns the dereferenced Image if it does exist, or raises a ClosedImageError otherwise.

Exc:ClosedImageError when the parent Image has been destroyed
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.

class wand.image.Metadata(image)

Class that implements dict-like read-only access to image metadata like EXIF or IPTC headers.

Parameters:image (Image) – an image instance

Note

You don’t have to use this by yourself. Use Image.metadata property instead.

New in version 0.3.0.

class wand.image.OptionDict(image)

Mutable mapping of the image internal options. See available options in OPTIONS constant.

New in version 0.3.0.

wand.image.manipulative(function)

Mark the operation manipulating itself instead of returning new one.

wand.color — Colors

New in version 0.1.2.

class wand.color.Color(string=None, raw=None)

Color value.

Unlike any other objects in Wand, its resource management can be implicit when it used outside of with block. In these case, its resource are allocated for every operation which requires a resource and destroyed immediately. Of course it is inefficient when the operations are much, so to avoid it, you should use color objects inside of with block explicitly e.g.:

red_count = 0
with Color('#f00') as red:
    with Image(filename='image.png') as img:
        for row in img:
            for col in row:
                if col == red:
                    red_count += 1
Parameters:string (basestring) – a color namel string e.g. 'rgb(255, 255, 255)', '#fff', 'white'. see ImageMagick Color Names doc also

Changed in version 0.3.0: Color objects become hashable.

See also

ImageMagick Color Names
The color can then be given as a color name (there is a limited but large set of these; see below) or it can be given as a set of numbers (in decimal or hexadecimal), each corresponding to a channel in an RGB or RGBA color model. HSL, HSLA, HSB, HSBA, CMYK, or CMYKA color models may also be specified. These topics are briefly described in the sections below.
== (other)

Equality operator.

Param other:a color another one
Type color:Color
Returns:True only if two images equal.
Rtype:bool
alpha

(numbers.Real) Alpha value, from 0.0 to 1.0.

alpha_int8

(numbers.Integral) Alpha value as 8bit integer which is a common style. From 0 to 255.

New in version 0.3.0.

alpha_quantum

(numbers.Integral) Alpha value. Scale depends on QUANTUM_DEPTH.

New in version 0.3.0.

blue

(numbers.Real) Blue, from 0.0 to 1.0.

blue_int8

(numbers.Integral) Blue as 8bit integer which is a common style. From 0 to 255.

New in version 0.3.0.

blue_quantum

(numbers.Integral) Blue. Scale depends on QUANTUM_DEPTH.

New in version 0.3.0.

static c_equals(a, b)

Raw level version of equality test function for two pixels.

Parameters:
Returns:

True only if two pixels equal

Return type:

bool

Note

It’s only for internal use. Don’t use it directly. Use == operator of Color instead.

green

(numbers.Real) Green, from 0.0 to 1.0.

green_int8

(numbers.Integral) Green as 8bit integer which is a common style. From 0 to 255.

New in version 0.3.0.

green_quantum

(numbers.Integral) Green. Scale depends on QUANTUM_DEPTH.

New in version 0.3.0.

normalized_string

(basestring) The normalized string representation of the color. The same color is always represented to the same string.

New in version 0.3.0.

red

(numbers.Real) Red, from 0.0 to 1.0.

red_int8

(numbers.Integral) Red as 8bit integer which is a common style. From 0 to 255.

New in version 0.3.0.

red_quantum

(numbers.Integral) Red. Scale depends on QUANTUM_DEPTH.

New in version 0.3.0.

string

(basestring) The string representation of the color.

wand.color.scale_quantum_to_int8(quantum)

Straightforward port of ScaleQuantumToChar() inline function.

Parameters:quantum (numbers.Integral) – quantum value
Returns:8bit integer of the given quantum value
Return type:numbers.Integral

New in version 0.3.0.

wand.font — Fonts

New in version 0.3.0.

Font is an object which takes the path of font file, size, color, and whether to use antialiasing. If you want to use font by its name rather than the file path, use TTFQuery package. The font path resolution by its name is a very complicated problem to achieve.

See also

TTFQuery — Find and Extract Information from TTF Files

TTFQuery builds on the FontTools-TTX package to allow the Python programmer to accomplish a number of tasks:

  • query the system to find installed fonts
  • retrieve metadata about any TTF font file
    • this includes the glyph outlines (shape) of individual code-points, which allows for rendering the glyphs in 3D (such as is done in OpenGLContext)
  • lookup/find fonts by:
    • abstract family type
    • proper font name
  • build simple metadata registries for run-time font matching
class wand.font.Font

Font struct which is a subtype of tuple.

Parameters:
  • path (str, basestring) – the path of the font file
  • size (numbers.Real) – the size of typeface. 0 by default which means autosized
  • color (Color) – the color of typeface. black by default
  • antialias (bool) – whether to use antialiasing. True by default

Changed in version 0.3.9: The size parameter becomes optional. Its default value is 0, which means autosized.

antialias

(bool) Whether to apply antialiasing (True) or not (False).

color

(wand.color.Color) The font color.

path

(basestring) The path of font file.

size

(numbers.Real) The font size in pixels.

wand.drawing — Drawings

The module provides some vector drawing functions.

New in version 0.3.0.

wand.drawing.CLIP_PATH_UNITS = ('undefined_path_units', 'user_space', 'user_space_on_use', 'object_bounding_box')

(collections.Sequence) The list of clip path units

  • 'undefined_path_units'
  • 'user_space'
  • 'user_space_on_use'
  • 'object_bounding_box'
wand.drawing.FILL_RULE_TYPES = ('undefined', 'evenodd', 'nonzero')

(collections.Sequence) The list of fill-rule types.

  • 'undefined'
  • 'evenodd'
  • 'nonzero'
wand.drawing.FONT_METRICS_ATTRIBUTES = ('character_width', 'character_height', 'ascender', 'descender', 'text_width', 'text_height', 'maximum_horizontal_advance', 'x1', 'y1', 'x2', 'y2', 'x', 'y')

(collections.Sequence) The attribute names of font metrics.

wand.drawing.GRAVITY_TYPES = ('forget', 'north_west', 'north', 'north_east', 'west', 'center', 'east', 'south_west', 'south', 'south_east', 'static')

(collections.Sequence) The list of text gravity types.

  • 'forget'
  • 'north_west'
  • 'north'
  • 'north_east'
  • 'west'
  • 'center'
  • 'east'
  • 'south_west'
  • 'south'
  • 'south_east'
  • 'static'
wand.drawing.LINE_CAP_TYPES = ('undefined', 'butt', 'round', 'square')

(collections.Sequence) The list of LineCap types

  • 'undefined;
  • 'butt'
  • 'round'
  • 'square'
wand.drawing.LINE_JOIN_TYPES = ('undefined', 'miter', 'round', 'bevel')

(collections.Sequence) The list of LineJoin types

  • 'undefined'
  • 'miter'
  • 'round'
  • 'bevel'
wand.drawing.PAINT_METHOD_TYPES = ('undefined', 'point', 'replace', 'floodfill', 'filltoborder', 'reset')

(collections.Sequence) The list of paint method types.

  • 'undefined'
  • 'point'
  • 'replace'
  • 'floodfill'
  • 'filltoborder'
  • 'reset'
wand.drawing.STRETCH_TYPES = ('undefined', 'normal', 'ultra_condensed', 'extra_condensed', 'condensed', 'semi_condensed', 'semi_expanded', 'expanded', 'extra_expanded', 'ultra_expanded', 'any')

(collections.Sequence) The list of stretch types for fonts

  • 'undefined;
  • 'normal'
  • 'ultra_condensed'
  • 'extra_condensed'
  • 'condensed'
  • 'semi_condensed'
  • 'semi_expanded'
  • 'expanded'
  • 'extra_expanded'
  • 'ultra_expanded'
  • 'any'
wand.drawing.STYLE_TYPES = ('undefined', 'normal', 'italic', 'oblique', 'any')

(collections.Sequence) The list of style types for fonts

  • 'undefined;
  • 'normal'
  • 'italic'
  • 'oblique'
  • 'any'
wand.drawing.TEXT_ALIGN_TYPES = ('undefined', 'left', 'center', 'right')

(collections.Sequence) The list of text align types.

  • 'undefined'
  • 'left'
  • 'center'
  • 'right'
wand.drawing.TEXT_DECORATION_TYPES = ('undefined', 'no', 'underline', 'overline', 'line_through')

(collections.Sequence) The list of text decoration types.

  • 'undefined'
  • 'no'
  • 'underline'
  • 'overline'
  • 'line_through'
wand.drawing.TEXT_DIRECTION_TYPES = ('undefined', 'right_to_left', 'left_to_right')

(collections.Sequence) The list of text direction types.

  • 'undefined'
  • 'right_to_left'
  • 'left_to_right'
class wand.drawing.Drawing(drawing=None)

Drawing object. It maintains several vector drawing instructions and can get drawn into zero or more Image objects by calling it.

For example, the following code draws a diagonal line to the image:

with Drawing() as draw:
    draw.line((0, 0), image.size)
    draw(image)
Parameters:drawing (Drawing) – an optional drawing object to clone. use clone() method rather than this parameter

New in version 0.3.0.

affine(matrix)

Adjusts the current affine transformation matrix with the specified affine transformation matrix. Note that the current affine transform is adjusted rather than replaced.

                                  | sx  rx  0 |
| x', y', 1 |  =  | x, y, 1 |  *  | ry  sy  0 |
                                  | tx  ty  1 |
Parameters:matrix (collections.Sequence) – a list of Real to define affine matrix [sx, rx, ry, sy, tx, ty]

New in version 0.4.0.

arc(start, end, degree)

Draws a arc using the current stroke_color, stroke_width, and fill_color.

Parameters:
  • start (Sequence) – (Real, numbers.Real) pair which represents starting x and y of the arc
  • end (Sequence) – (Real, numbers.Real) pair which represents ending x and y of the arc
  • degree (Sequence) – (Real, numbers.Real) pair which represents starting degree, and ending degree

New in version 0.4.0.

bezier(points=None)

Draws a bezier curve through a set of points on the image, using the specified array of coordinates.

At least four points should be given to complete a bezier path. The first & forth point being the start & end point, and the second & third point controlling the direction & curve.

Example bezier on image

with Drawing() as draw:
    points = [(40,10), # Start point
              (20,50), # First control
              (90,10), # Second control
              (70,40)] # End point
    draw.stroke_color = Color('#000')
    draw.fill_color = Color('#fff')
    draw.bezier(points)
    draw.draw(image)
Parameters:points (list) – list of x,y tuples

New in version 0.4.0.

border_color

(Color) the current border color. It also can be set. This attribute controls the behavior of color() during 'filltoborder' operation.

New in version 0.4.0.

circle(origin, perimeter)

Draws a circle from origin to perimeter

Parameters:
  • origin (collections.Sequence) – (Real, numbers.Real) pair which represents origin x and y of circle
  • perimeter (collections.Sequence) – (Real, numbers.Real) pair which represents perimeter x and y of circle

New in version 0.4.0.

clip_path

(basestring) The current clip path. It also can be set.

New in version 0.4.0.

clip_rule

(basestring) The current clip rule. It also can be set. It’s a string value from FILL_RULE_TYPES list.

New in version 0.4.0.

clip_units

(basestring) The current clip units. It also can be set. It’s a string value from CLIP_PATH_UNITS list.

New in version 0.4.0.

clone()

Copies a drawing object.

Returns:a duplication
Return type:Drawing
color(x=None, y=None, paint_method='undefined')

Draws a color on the image using current fill color, starting at specified position & method.

Available methods in wand.drawing.PAINT_METHOD_TYPES:

  • 'undefined'
  • 'point'
  • 'replace'
  • 'floodfill'
  • 'filltoborder'
  • 'reset'

New in version 0.4.0.

comment(message=None)

Adds a comment to the vector stream.

Parameters:message (basestring) – the comment to set.

New in version 0.4.0.

composite(operator, left, top, width, height, image)

Composites an image onto the current image, using the specified composition operator, specified position, and at the specified size.

Parameters:
  • operator – the operator that affects how the composite is applied to the image. available values can be found in the COMPOSITE_OPERATORS list
  • typeCOMPOSITE_OPERATORS
  • left (numbers.Real) – the column offset of the composited drawing source
  • top (numbers.Real) – the row offset of the composited drawing source
  • width (numbers.Real) – the total columns to include in the composited source
  • height (numbers.Real) – the total rows to include in the composited source

New in version 0.4.0.

draw(image)

Renders the current drawing into the image. You can simply call Drawing instance rather than calling this method. That means the following code which calls Drawing object itself:

drawing(image)

is equivalent to the following code which calls draw() method:

drawing.draw(image)
Parameters:image (Image) – the image to be drawn
ellipse(origin, radius, rotation=(0, 360))

Draws a ellipse at origin with independent x & y radius. Ellipse can be partial by setting start & end rotation.

Parameters:
  • origin (collections.Sequence) – (Real, numbers.Real) pair which represents origin x and y of circle
  • radius (collections.Sequence) – (Real, numbers.Real) pair which represents radius x and radius y of circle
  • rotation (collections.Sequence) – (Real, numbers.Real) pair which represents start and end of ellipse. Default (0,360)

New in version 0.4.0.

fill_color

(Color) The current color to fill. It also can be set.

fill_opacity

(Real) The current fill opacity. It also can be set.

New in version 0.4.0.

fill_rule

(basestring) The current fill rule. It can also be set. It’s a string value from FILL_RULE_TYPES list.

New in version 0.4.0.

font

(basestring) The current font name. It also can be set.

font_family

(basestring) The current font family. It also can be set.

New in version 0.4.0.

font_resolution

(Sequence) The current font resolution. It also can be set.

New in version 0.4.0.

font_size

(numbers.Real) The font size. It also can be set.

font_stretch

(basestring) The current font stretch variation. It also can be set, but will only apply if the font-family or encoder supports the stretch type.

New in version 0.4.0.

font_style

(basestring) The current font style. It also can be set, but will only apply if the font-family supports the style.

New in version 0.4.0.

font_weight

(Integral) The current font weight. It also can be set.

New in version 0.4.0.

get_font_metrics(image, text, multiline=False)

Queries font metrics from the given text.

Parameters:
  • image (Image) – the image to be drawn
  • text (basestring) – the text string for get font metrics.
  • multiline (boolean) – text is multiline or not
gravity

(basestring) The text placement gravity used when annotating with text. It’s a string from GRAVITY_TYPES list. It also can be set.

line(start, end)

Draws a line start to end.

Parameters:
matte(x=None, y=None, paint_method='undefined')

Paints on the image’s opacity channel in order to set effected pixels to transparent.

To influence the opacity of pixels. The available methods are:
  • 'undefined'
  • 'point'
  • 'replace'
  • 'floodfill'
  • 'filltoborder'
  • 'reset'

New in version 0.4.0.

opacity

(Real) returns the opacity used when drawing with the fill or stroke color or texture. Fully opaque is 1.0. This method only affects vector graphics, and is experimental. To set the opacity of a drawing, use Drawing.fill_opacity & Drawing.stroke_opacity

New in version 0.4.0.

path_close()

Adds a path element to the current path which closes the current subpath by drawing a straight line from the current point to the current subpath’s most recent starting point.

New in version 0.4.0.

path_curve(to=None, controls=None, smooth=False, relative=False)

Draws a cubic Bezier curve from the current point to given to (x,y) coordinate using controls points at the beginning and the end of the curve. If smooth is set to True, only one controls is expected and the previous control is used, else two pair of coordinates are expected to define the control points. The to coordinate then becomes the new current point.

Parameters:
  • to (collections.Sequence) – (Real, numbers.Real) pair which represents coordinates to draw to
  • controls (collections.Sequence) – (Real, numbers.Real) coordinate to used to influence curve
  • smooth (bool) – bool assume last defined control coordinate
  • relative (bool) – treat given coordinates as relative to current point

New in version 0.4.0.

path_curve_to_quadratic_bezier(to=None, control=None, smooth=False, relative=False)

Draws a quadratic Bezier curve from the current point to given to coordinate. The control point is assumed to be the reflection of the control point on the previous command if smooth is True, else a pair of control coordinates must be given. Each coordinates can be relative, or absolute, to the current point by setting the relative flag. The to coordinate then becomes the new current point, and the control coordinate will be assumed when called again when smooth is set to true.

Parameters:
  • to (collections.Sequence) – (Real, numbers.Real) pair which represents coordinates to draw to
  • control (collections.Sequence) – (Real, numbers.Real) coordinate to used to influence curve
  • smooth (bool) – assume last defined control coordinate
  • relative (bool) – treat given coordinates as relative to current point

New in version 0.4.0.

path_elliptic_arc(to=None, radius=None, rotation=0.0, large_arc=False, clockwise=False, relative=False)

Draws an elliptical arc from the current point to given to coordinates. The to coordinates can be relative, or absolute, to the current point by setting the relative flag. The size and orientation of the ellipse are defined by two radii (rx, ry) in radius and an rotation parameters, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center of the ellipse is calculated automagically to satisfy the constraints imposed by the other parameters. large_arc and clockwise contribute to the automatic calculations and help determine how the arc is drawn. If large_arc is True then draw the larger of the available arcs. If clockwise is true, then draw the arc matching a clock-wise rotation.

Parameters:
  • to (collections.Sequence) – (Real, numbers.Real) pair which represents coordinates to draw to
  • radius (collections.Sequence) – (Real, numbers.Real) pair which represents the radii of the ellipse to draw
  • rotate (Real) – degree to rotate ellipse on x-axis
  • large_arc (bool) – draw largest available arc
  • clockwise (bool) – draw arc path clockwise from start to target
  • relative (bool) – treat given coordinates as relative to current point

New in version 0.4.0.

path_finish()

Terminates the current path.

New in version 0.4.0.

path_horizontal_line(x=None, relative=False)

Draws a horizontal line path from the current point to the target point. Given x parameter can be relative, or absolute, to the current point by setting the relative flag. The target point then becomes the new current point.

Parameters:
  • x (Real) – Real x-axis point to draw to.
  • relative (bool) – bool treat given point as relative to current point

New in version 0.4.0.

path_line(to=None, relative=False)

Draws a line path from the current point to the given to coordinate. The to coordinates can be relative, or absolute, to the current point by setting the relative flag. The coordinate then becomes the new current point.

Parameters:
  • to (collections.Sequence) – (Real, numbers.Real) pair which represents coordinates to draw to.
  • relative (bool) – bool treat given coordinates as relative to current point

New in version 0.4.0.

path_move(to=None, relative=False)

Starts a new sub-path at the given coordinates. Given to parameter can be relative, or absolute, by setting the relative flag.

Parameters:
  • to (collections.Sequence) – (Real, numbers.Real) pair which represents coordinates to draw to.
  • relative (bool) – bool treat given coordinates as relative to current point

New in version 0.4.0.

path_start()

Declares the start of a path drawing list which is terminated by a matching path_finish() command. All other path_* commands must be enclosed between a path_start() and a path_finish() command. This is because path drawing commands are subordinate commands and they do not function by themselves.

New in version 0.4.0.

path_vertical_line(y=None, relative=False)

Draws a vertical line path from the current point to the target point. Given y parameter can be relative, or absolute, to the current point by setting the relative flag. The target point then becomes the new current point.

Parameters:
  • y (Real) – Real y-axis point to draw to.
  • relative (bool) – bool treat given point as relative to current point

New in version 0.4.0.

point(x, y)

Draws a point at given x and y

Parameters:

New in version 0.4.0.

polygon(points=None)

Draws a polygon using the current stoke_color, stroke_width, and fill_color, using the specified array of coordinates.

Example polygon on image

with Drawing() as draw:
    points = [(40,10), (20,50), (90,10), (70,40)]
    draw.polygon(points)
    draw.draw(image)
Parameters:points (list) – list of x,y tuples

New in version 0.4.0.

polyline(points=None)

Draws a polyline using the current stoke_color, stroke_width, and fill_color, using the specified array of coordinates.

Identical to polygon, but without closed stroke line.

Parameters:points (list) – list of x,y tuples

New in version 0.4.0.

pop()

Pop destroys the current drawing wand and returns to the previously pushed drawing wand. Multiple drawing wands may exist. It is an error to attempt to pop more drawing wands than have been pushed, and it is proper form to pop all drawing wands which have been pushed.

Returns:success of pop operation
Return type:bool

New in version 0.4.0.

pop_clip_path()

Terminates a clip path definition.

New in version 0.4.0.

pop_defs()

Terminates a definition list.

New in version 0.4.0.

pop_pattern()

Terminates a pattern definition.

New in version 0.4.0.

push()

Push clones the current drawing wand to create a new drawing wand. The original drawing wand(s) may be returned to by invoking Drawing.pop. The drawing wands are stored on a drawing wand stack. For every Pop there must have already been an equivalent Push.

Returns:success of push operation
Return type:bool

New in version 0.4.0.

push_clip_path(clip_mask_id)

Starts a clip path definition which is comprised of any number of drawing commands and terminated by a Drawing.pop_clip_path command.

Parameters:clip_mask_id (basestring) – string identifier to associate with the clip path.

New in version 0.4.0.

push_defs()

Indicates that commands up to a terminating Drawing.pop_defs command create named elements (e.g. clip-paths, textures, etc.) which may safely be processed earlier for the sake of efficiency.

New in version 0.4.0.

push_pattern(pattern_id, left, top, width, height)

Indicates that subsequent commands up to a Drawing.pop_pattern command comprise the definition of a named pattern. The pattern space is assigned top left corner coordinates, a width and height, and becomes its own drawing space. Anything which can be drawn may be used in a pattern definition. Named patterns may be used as stroke or brush definitions.

Parameters:
  • pattern_id (basestring) – a unique identifier for the pattern.
  • left (numbers.Real) – x ordinate of top left corner.
  • top (numbers.Real) – y ordinate of top left corner.
  • width (numbers.Real) – width of pattern space.
  • height (numbers.Real) – height of pattern space.
Returns:

success of push operation

Return type:

bool

New in version 0.4.0.

rectangle(left=None, top=None, right=None, bottom=None, width=None, height=None, radius=None, xradius=None, yradius=None)

Draws a rectangle using the current stroke_color, stroke_width, and fill_color.

+--------------------------------------------------+
|              ^                         ^         |
|              |                         |         |
|             top                        |         |
|              |                         |         |
|              v                         |         |
| <-- left --> +-------------------+  bottom       |
|              |             ^     |     |         |
|              | <-- width --|---> |     |         |
|              |           height  |     |         |
|              |             |     |     |         |
|              |             v     |     |         |
|              +-------------------+     v         |
| <--------------- right ---------->               |
+--------------------------------------------------+
Parameters:
  • left (numbers.Real) – x-offset of the rectangle to draw
  • top (numbers.Real) – y-offset of the rectangle to draw
  • right (numbers.Real) – second x-offset of the rectangle to draw. this parameter and width parameter are exclusive each other
  • bottom (numbers.Real) – second y-offset of the rectangle to draw. this parameter and height parameter are exclusive each other
  • width (numbers.Real) – the width of the rectangle to draw. this parameter and right parameter are exclusive each other
  • height (numbers.Real) – the height of the rectangle to draw. this parameter and bottom parameter are exclusive each other
  • radius (numbers.Real) – the corner rounding. this is a short-cut for setting both xradius, and yradius
  • xradius (numbers.Real) – the xradius corner in horizontal direction.
  • yradius (numbers.Real) – the yradius corner in vertical direction.

New in version 0.3.6.

Changed in version 0.4.0: Radius keywords added to create rounded rectangle.

rotate(degree)

Applies the specified rotation to the current coordinate space.

Parameters:degree (Real) – degree to rotate

New in version 0.4.0.

scale(x=None, y=None)

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

Parameters:
  • x (Real) – Horizontal scale factor
  • y (Real) – Vertical scale factor

New in version 0.4.0.

set_fill_pattern_url(url)

Sets the URL to use as a fill pattern for filling objects. Only local URLs (“#identifier”) are supported at this time. These local URLs are normally created by defining a named fill pattern with Drawing.push_pattern & Drawing.pop_pattern.

Parameters:url (basestring) – URL to use to obtain fill pattern.

New in version 0.4.0.

set_stroke_pattern_url(url)

Sets the pattern used for stroking object outlines. Only local URLs (“#identifier”) are supported at this time. These local URLs are normally created by defining a named stroke pattern with Drawing.push_pattern & Drawing.pop_pattern.

Parameters:url (basestring) – URL to use to obtain stroke pattern.

New in version 0.4.0.

skew(x=None, y=None)

Skews the current coordinate system in the horizontal direction if x is given, and vertical direction if y is given.

Parameters:
  • x (Real) – Skew horizontal direction
  • y (Real) – Skew vertical direction

New in version 0.4.0.

stroke_antialias

(bool) Controls whether stroked outlines are antialiased. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

It also can be set.

New in version 0.4.0.

stroke_color

(Color) The current color of stroke. It also can be set.

New in version 0.3.3.

stroke_dash_array

(Sequence) - (numbers.Real) An array representing the pattern of dashes & gaps used to stroke paths. It also can be set.

New in version 0.4.0.

stroke_dash_offset

(numbers.Real) The stroke dash offset. It also can be set.

New in version 0.4.0.

stroke_line_cap

(basestring) The stroke line cap. It also can be set.

New in version 0.4.0.

stroke_line_join

(basestring) The stroke line join. It also can be set.

New in version 0.4.0.

stroke_miter_limit

(Integral) The current miter limit. It also can be set.

New in version 0.4.0.

stroke_opacity

(Real) The current stroke opacity. It also can be set.

New in version 0.4.0.

stroke_width

(numbers.Real) The stroke width. It also can be set.

New in version 0.3.3.

text(x, y, body)

Writes a text body into (x, y).

Parameters:
  • x (numbers.Integral) – the left offset where to start writing a text
  • y (numbers.Integral) – the baseline where to start writing text
  • body (basestring) – the body string to write
text_alignment

(basestring) The current text alignment setting. It’s a string value from TEXT_ALIGN_TYPES list. It also can be set.

text_antialias

(bool) The boolean value which represents whether antialiasing is used for text rendering. It also can be set to True or False to switch the setting.

text_decoration

(basestring) The text decoration setting, a string from TEXT_DECORATION_TYPES list. It also can be set.

text_direction

(basestring) The text direction setting. a string from TEXT_DIRECTION_TYPES list. It also can be set.

text_encoding

(basestring) The internally used text encoding setting. Although it also can be set, but it’s not encouraged.

text_interline_spacing

(numbers.Real) The setting of the text line spacing. It also can be set.

text_interword_spacing

(numbers.Real) The setting of the word spacing. It also can be set.

text_kerning

(numbers.Real) The setting of the text kerning. It also can be set.

text_under_color

(Color) The color of a background rectangle to place under text annotations. It also can be set.

translate(x=None, y=None)

Applies a translation to the current coordinate system which moves the coordinate system origin to the specified coordinate.

Parameters:
  • x (Real) – Skew horizontal direction
  • y (Real) – Skew vertical direction

New in version 0.4.0.

vector_graphics

(basestring) The XML text of the Vector Graphics. It also can be set. The drawing-wand XML is experimental, and subject to change.

Setting this property to None will reset all vector graphic properties to the default state.

New in version 0.4.0.

viewbox(left, top, right, bottom)

Viewbox sets the overall canvas size to be recorded with the drawing vector data. Usually this will be specified using the same size as the canvas image. When the vector data is saved to SVG or MVG formats, the viewbox is use to specify the size of the canvas image that a viewer will render the vector data on.

Parameters:
  • left (Integral) – the left most point of the viewbox.
  • top (Integral) – the top most point of the viewbox.
  • right (Integral) – the right most point of the viewbox.
  • bottom (Integral) – the bottom most point of the viewbox.

New in version 0.4.0.

class wand.drawing.FontMetrics(character_width, character_height, ascender, descender, text_width, text_height, maximum_horizontal_advance, x1, y1, x2, y2, x, y)

The tuple subtype which consists of font metrics data.

ascender

Alias for field number 2

character_height

Alias for field number 1

character_width

Alias for field number 0

descender

Alias for field number 3

maximum_horizontal_advance

Alias for field number 6

text_height

Alias for field number 5

text_width

Alias for field number 4

x

Alias for field number 11

x1

Alias for field number 7

x2

Alias for field number 9

y

Alias for field number 12

y1

Alias for field number 8

y2

Alias for field number 10

wand.sequence — Sequences

New in version 0.3.0.

class wand.sequence.Sequence(image)

The list-like object that contains every SingleImage in the Image container. It implements collections.Sequence prototocol.

New in version 0.3.0.

append(image)

S.append(object) – append object to the end of the sequence

current_index

(numbers.Integral) The current index of its internal iterator.

Note

It’s only for internal use.

extend(images, offset=None)

S.extend(iterable) – extend sequence by appending elements from the iterable

index_context(**kwds)

Scoped setter of current_index. Should be used for with statement e.g.:

with image.sequence.index_context(3):
    print(image.size)

Note

It’s only for internal use.

insert(index, image)

S.insert(index, object) – insert object before index

class wand.sequence.SingleImage(wand, container, c_original_resource)

Each single image in Image container. For example, it can be a frame of GIF animation.

Note that all changes on single images are invisible to their containers until they are close()d (destroy()ed).

New in version 0.3.0.

container = None

(wand.image.Image) The container image.

delay

(numbers.Integral) The delay to pause before display the next image (in the sequence of its container). It’s hundredths of a second.

destroy()

Cleans up the resource explicitly. If you use the resource in with statement, it was called implicitly so have not to call it.

index

(numbers.Integral) The index of the single image in the container image.

wand.resource — Global resource management

There is the global resource to manage in MagickWand API. This module implements automatic global resource management through reference counting.

wand.resource.genesis()

Instantiates the MagickWand API.

Warning

Don’t call this function directly. Use increment_refcount() and decrement_refcount() functions instead.

wand.resource.terminus()

Cleans up the MagickWand API.

Warning

Don’t call this function directly. Use increment_refcount() and decrement_refcount() functions instead.

wand.resource.increment_refcount()

Increments the reference_count and instantiates the MagickWand API if it is the first use.

wand.resource.decrement_refcount()

Decrements the reference_count and cleans up the MagickWand API if it will be no more used.

class wand.resource.Resource

Abstract base class for MagickWand object that requires resource management. Its all subclasses manage the resource semiautomatically and support with statement as well:

with Resource() as resource:
    # use the resource...
    pass

It doesn’t implement constructor by itself, so subclasses should implement it. Every constructor should assign the pointer of its resource data into resource attribute inside of with allocate() context. For example:

class Pizza(Resource):
    '''My pizza yummy.'''

    def __init__(self):
        with self.allocate():
            self.resource = library.NewPizza()

New in version 0.1.2.

allocate(**kwds)

Allocates the memory for the resource explicitly. Its subclasses should assign the created resource into resource attribute inside of this context. For example:

with resource.allocate():
    resource.resource = library.NewResource()
c_clear_exception = NotImplemented

(ctypes.CFUNCTYPE) The ctypes function that clears an exception of the resource.

Note

It is an abstract attribute that has to be implemented in the subclass.

c_destroy_resource = NotImplemented

(ctypes.CFUNCTYPE) The ctypes function that destroys the resource.

Note

It is an abstract attribute that has to be implemented in the subclass.

c_get_exception = NotImplemented

(ctypes.CFUNCTYPE) The ctypes function that gets an exception from the resource.

Note

It is an abstract attribute that has to be implemented in the subclass.

c_is_resource = NotImplemented

(ctypes.CFUNCTYPE) The ctypes predicate function that returns whether the given pointer (that contains a resource data usuaully) is a valid resource.

Note

It is an abstract attribute that has to be implemented in the subclass.

destroy()

Cleans up the resource explicitly. If you use the resource in with statement, it was called implicitly so have not to call it.

get_exception()

Gets a current exception instance.

Returns:a current exception. it can be None as well if any errors aren’t occurred
Return type:wand.exceptions.WandException
raise_exception(stacklevel=1)

Raises an exception or warning if it has occurred.

resource

Internal pointer to the resource instance. It may raise DestroyedResourceError when the resource has destroyed already.

exception wand.resource.DestroyedResourceError

An error that rises when some code tries access to an already destroyed resource.

Changed in version 0.3.0: It becomes a subtype of wand.exceptions.WandException.

wand.exceptions — Errors and warnings

This module maps MagickWand API’s errors and warnings to Python’s native exceptions and warnings. You can catch all MagickWand errors using Python’s natural way to catch errors.

New in version 0.1.1.

exception wand.exceptions.BaseError

Bases: wand.exceptions.WandException

Base class for Wand-related errors.

New in version 0.4.4.

exception wand.exceptions.BaseFatalError

Bases: wand.exceptions.WandException

Base class for Wand-related fatal errors.

New in version 0.4.4.

exception wand.exceptions.BaseWarning

Bases: wand.exceptions.WandException, exceptions.Warning

Base class for Wand-related warnings.

New in version 0.4.4.

exception wand.exceptions.BlobError

Bases: wand.exceptions.BaseError, exceptions.IOError

A binary large object could not be allocated, read, or written.

exception wand.exceptions.BlobFatalError

Bases: wand.exceptions.BaseFatalError, exceptions.IOError

A binary large object could not be allocated, read, or written.

exception wand.exceptions.BlobWarning

Bases: wand.exceptions.BaseWarning, exceptions.IOError

A binary large object could not be allocated, read, or written.

wand.exceptions.CODE_MAP = [(<class 'wand.exceptions.BaseWarning'>, 'Warning'), (<class 'wand.exceptions.BaseError'>, 'Error'), (<class 'wand.exceptions.BaseFatalError'>, 'FatalError')]

(list) The list of (base_class, suffix) pairs (for each code). It would be zipped with DOMAIN_MAP pairs’ last element.

exception wand.exceptions.CacheError

Bases: wand.exceptions.BaseError

Pixels could not be read or written to the pixel cache.

exception wand.exceptions.CacheFatalError

Bases: wand.exceptions.BaseFatalError

Pixels could not be read or written to the pixel cache.

exception wand.exceptions.CacheWarning

Bases: wand.exceptions.BaseWarning

Pixels could not be read or written to the pixel cache.

exception wand.exceptions.CoderError

Bases: wand.exceptions.BaseError

There was a problem with an image coder.

exception wand.exceptions.CoderFatalError

Bases: wand.exceptions.BaseFatalError

There was a problem with an image coder.

exception wand.exceptions.CoderWarning

Bases: wand.exceptions.BaseWarning

There was a problem with an image coder.

exception wand.exceptions.ConfigureError

Bases: wand.exceptions.BaseError

There was a problem getting a configuration file.

exception wand.exceptions.ConfigureFatalError

Bases: wand.exceptions.BaseFatalError

There was a problem getting a configuration file.

exception wand.exceptions.ConfigureWarning

Bases: wand.exceptions.BaseWarning

There was a problem getting a configuration file.

exception wand.exceptions.CorruptImageError

Bases: wand.exceptions.BaseError, exceptions.ValueError

The image file may be corrupt.

exception wand.exceptions.CorruptImageFatalError

Bases: wand.exceptions.BaseFatalError, exceptions.ValueError

The image file may be corrupt.

exception wand.exceptions.CorruptImageWarning

Bases: wand.exceptions.BaseWarning, exceptions.ValueError

The image file may be corrupt.

wand.exceptions.DOMAIN_MAP = [('ResourceLimit', 'A program resource is exhausted e.g. not enough memory.', (<type 'exceptions.MemoryError'>,), [300, 400, 700]), ('Type', 'A font is unavailable; a substitution may have occurred.', (), [305, 405, 705]), ('Option', 'A command-line option was malformed.', (), [310, 410, 710]), ('Delegate', 'An ImageMagick delegate failed to complete.', (), [315, 415, 715]), ('MissingDelegate', 'The image type can not be read or written because the appropriate; delegate is missing.', (<type 'exceptions.ImportError'>,), [320, 420, 720]), ('CorruptImage', 'The image file may be corrupt.', (<type 'exceptions.ValueError'>,), [325, 425, 725]), ('FileOpen', 'The image file could not be opened for reading or writing.', (<type 'exceptions.IOError'>,), [330, 430, 730]), ('Blob', 'A binary large object could not be allocated, read, or written.', (<type 'exceptions.IOError'>,), [335, 435, 735]), ('Stream', 'There was a problem reading or writing from a stream.', (<type 'exceptions.IOError'>,), [340, 440, 740]), ('Cache', 'Pixels could not be read or written to the pixel cache.', (), [345, 445, 745]), ('Coder', 'There was a problem with an image coder.', (), [350, 450, 750]), ('Module', 'There was a problem with an image module.', (), [355, 455, 755]), ('Draw', 'A drawing operation failed.', (), [360, 460, 760]), ('Image', 'The operation could not complete due to an incompatible image.', (), [365, 465, 765]), ('Wand', 'There was a problem specific to the MagickWand API.', (), [370, 470, 770]), ('Random', 'There is a problem generating a true or pseudo-random number.', (), [375, 475, 775]), ('XServer', 'An X resource is unavailable.', (), [380, 480, 780]), ('Monitor', 'There was a problem activating the progress monitor.', (), [385, 485, 785]), ('Registry', 'There was a problem getting or setting the registry.', (), [390, 490, 790]), ('Configure', 'There was a problem getting a configuration file.', (), [395, 495, 795]), ('Policy', 'A policy denies access to a delegate, coder, filter, path, or resource.', (), [399, 499, 799])]

(list) A list of error/warning domains, these descriptions and codes. The form of elements is like: (domain name, description, codes).

exception wand.exceptions.DelegateError

Bases: wand.exceptions.BaseError

An ImageMagick delegate failed to complete.

exception wand.exceptions.DelegateFatalError

Bases: wand.exceptions.BaseFatalError

An ImageMagick delegate failed to complete.

exception wand.exceptions.DelegateWarning

Bases: wand.exceptions.BaseWarning

An ImageMagick delegate failed to complete.

exception wand.exceptions.DrawError

Bases: wand.exceptions.BaseError

A drawing operation failed.

exception wand.exceptions.DrawFatalError

Bases: wand.exceptions.BaseFatalError

A drawing operation failed.

exception wand.exceptions.DrawWarning

Bases: wand.exceptions.BaseWarning

A drawing operation failed.

exception wand.exceptions.FileOpenError

Bases: wand.exceptions.BaseError, exceptions.IOError

The image file could not be opened for reading or writing.

exception wand.exceptions.FileOpenFatalError

Bases: wand.exceptions.BaseFatalError, exceptions.IOError

The image file could not be opened for reading or writing.

exception wand.exceptions.FileOpenWarning

Bases: wand.exceptions.BaseWarning, exceptions.IOError

The image file could not be opened for reading or writing.

exception wand.exceptions.ImageError

Bases: wand.exceptions.BaseError

The operation could not complete due to an incompatible image.

exception wand.exceptions.ImageFatalError

Bases: wand.exceptions.BaseFatalError

The operation could not complete due to an incompatible image.

exception wand.exceptions.ImageWarning

Bases: wand.exceptions.BaseWarning

The operation could not complete due to an incompatible image.

exception wand.exceptions.MissingDelegateError

Bases: wand.exceptions.BaseError, exceptions.ImportError

The image type can not be read or written because the appropriate; delegate is missing.

exception wand.exceptions.MissingDelegateFatalError

Bases: wand.exceptions.BaseFatalError, exceptions.ImportError

The image type can not be read or written because the appropriate; delegate is missing.

exception wand.exceptions.MissingDelegateWarning

Bases: wand.exceptions.BaseWarning, exceptions.ImportError

The image type can not be read or written because the appropriate; delegate is missing.

exception wand.exceptions.ModuleError

Bases: wand.exceptions.BaseError

There was a problem with an image module.

exception wand.exceptions.ModuleFatalError

Bases: wand.exceptions.BaseFatalError

There was a problem with an image module.

exception wand.exceptions.ModuleWarning

Bases: wand.exceptions.BaseWarning

There was a problem with an image module.

exception wand.exceptions.MonitorError

Bases: wand.exceptions.BaseError

There was a problem activating the progress monitor.

exception wand.exceptions.MonitorFatalError

Bases: wand.exceptions.BaseFatalError

There was a problem activating the progress monitor.

exception wand.exceptions.MonitorWarning

Bases: wand.exceptions.BaseWarning

There was a problem activating the progress monitor.

exception wand.exceptions.OptionError

Bases: wand.exceptions.BaseError

A command-line option was malformed.

exception wand.exceptions.OptionFatalError

Bases: wand.exceptions.BaseFatalError

A command-line option was malformed.

exception wand.exceptions.OptionWarning

Bases: wand.exceptions.BaseWarning

A command-line option was malformed.

exception wand.exceptions.PolicyError

Bases: wand.exceptions.BaseError

A policy denies access to a delegate, coder, filter, path, or resource.

exception wand.exceptions.PolicyFatalError

Bases: wand.exceptions.BaseFatalError

A policy denies access to a delegate, coder, filter, path, or resource.

exception wand.exceptions.PolicyWarning

Bases: wand.exceptions.BaseWarning

A policy denies access to a delegate, coder, filter, path, or resource.

exception wand.exceptions.RandomError

Bases: wand.exceptions.BaseError

There is a problem generating a true or pseudo-random number.

exception wand.exceptions.RandomFatalError

Bases: wand.exceptions.BaseFatalError

There is a problem generating a true or pseudo-random number.

exception wand.exceptions.RandomWarning

Bases: wand.exceptions.BaseWarning

There is a problem generating a true or pseudo-random number.

exception wand.exceptions.RegistryError

Bases: wand.exceptions.BaseError

There was a problem getting or setting the registry.

exception wand.exceptions.RegistryFatalError

Bases: wand.exceptions.BaseFatalError

There was a problem getting or setting the registry.

exception wand.exceptions.RegistryWarning

Bases: wand.exceptions.BaseWarning

There was a problem getting or setting the registry.

exception wand.exceptions.ResourceLimitError

Bases: wand.exceptions.BaseError, exceptions.MemoryError

A program resource is exhausted e.g. not enough memory.

exception wand.exceptions.ResourceLimitFatalError

Bases: wand.exceptions.BaseFatalError, exceptions.MemoryError

A program resource is exhausted e.g. not enough memory.

exception wand.exceptions.ResourceLimitWarning

Bases: wand.exceptions.BaseWarning, exceptions.MemoryError

A program resource is exhausted e.g. not enough memory.

exception wand.exceptions.StreamError

Bases: wand.exceptions.BaseError, exceptions.IOError

There was a problem reading or writing from a stream.

exception wand.exceptions.StreamFatalError

Bases: wand.exceptions.BaseFatalError, exceptions.IOError

There was a problem reading or writing from a stream.

exception wand.exceptions.StreamWarning

Bases: wand.exceptions.BaseWarning, exceptions.IOError

There was a problem reading or writing from a stream.

wand.exceptions.TYPE_MAP = {300: <class 'wand.exceptions.ResourceLimitWarning'>, 305: <class 'wand.exceptions.TypeWarning'>, 310: <class 'wand.exceptions.OptionWarning'>, 315: <class 'wand.exceptions.DelegateWarning'>, 320: <class 'wand.exceptions.MissingDelegateWarning'>, 325: <class 'wand.exceptions.CorruptImageWarning'>, 330: <class 'wand.exceptions.FileOpenWarning'>, 335: <class 'wand.exceptions.BlobWarning'>, 340: <class 'wand.exceptions.StreamWarning'>, 345: <class 'wand.exceptions.CacheWarning'>, 350: <class 'wand.exceptions.CoderWarning'>, 355: <class 'wand.exceptions.ModuleWarning'>, 360: <class 'wand.exceptions.DrawWarning'>, 365: <class 'wand.exceptions.ImageWarning'>, 370: <class 'wand.exceptions.WandWarning'>, 375: <class 'wand.exceptions.RandomWarning'>, 380: <class 'wand.exceptions.XServerWarning'>, 385: <class 'wand.exceptions.MonitorWarning'>, 390: <class 'wand.exceptions.RegistryWarning'>, 395: <class 'wand.exceptions.ConfigureWarning'>, 399: <class 'wand.exceptions.PolicyWarning'>, 400: <class 'wand.exceptions.ResourceLimitError'>, 405: <class 'wand.exceptions.TypeError'>, 410: <class 'wand.exceptions.OptionError'>, 415: <class 'wand.exceptions.DelegateError'>, 420: <class 'wand.exceptions.MissingDelegateError'>, 425: <class 'wand.exceptions.CorruptImageError'>, 430: <class 'wand.exceptions.FileOpenError'>, 435: <class 'wand.exceptions.BlobError'>, 440: <class 'wand.exceptions.StreamError'>, 445: <class 'wand.exceptions.CacheError'>, 450: <class 'wand.exceptions.CoderError'>, 455: <class 'wand.exceptions.ModuleError'>, 460: <class 'wand.exceptions.DrawError'>, 465: <class 'wand.exceptions.ImageError'>, 470: <class 'wand.exceptions.WandError'>, 475: <class 'wand.exceptions.RandomError'>, 480: <class 'wand.exceptions.XServerError'>, 485: <class 'wand.exceptions.MonitorError'>, 490: <class 'wand.exceptions.RegistryError'>, 495: <class 'wand.exceptions.ConfigureError'>, 499: <class 'wand.exceptions.PolicyError'>, 700: <class 'wand.exceptions.ResourceLimitFatalError'>, 705: <class 'wand.exceptions.TypeFatalError'>, 710: <class 'wand.exceptions.OptionFatalError'>, 715: <class 'wand.exceptions.DelegateFatalError'>, 720: <class 'wand.exceptions.MissingDelegateFatalError'>, 725: <class 'wand.exceptions.CorruptImageFatalError'>, 730: <class 'wand.exceptions.FileOpenFatalError'>, 735: <class 'wand.exceptions.BlobFatalError'>, 740: <class 'wand.exceptions.StreamFatalError'>, 745: <class 'wand.exceptions.CacheFatalError'>, 750: <class 'wand.exceptions.CoderFatalError'>, 755: <class 'wand.exceptions.ModuleFatalError'>, 760: <class 'wand.exceptions.DrawFatalError'>, 765: <class 'wand.exceptions.ImageFatalError'>, 770: <class 'wand.exceptions.WandFatalError'>, 775: <class 'wand.exceptions.RandomFatalError'>, 780: <class 'wand.exceptions.XServerFatalError'>, 785: <class 'wand.exceptions.MonitorFatalError'>, 790: <class 'wand.exceptions.RegistryFatalError'>, 795: <class 'wand.exceptions.ConfigureFatalError'>, 799: <class 'wand.exceptions.PolicyFatalError'>}

(dict) The dictionary of (code, exc_type).

exception wand.exceptions.TypeError

Bases: wand.exceptions.BaseError

A font is unavailable; a substitution may have occurred.

exception wand.exceptions.TypeFatalError

Bases: wand.exceptions.BaseFatalError

A font is unavailable; a substitution may have occurred.

exception wand.exceptions.TypeWarning

Bases: wand.exceptions.BaseWarning

A font is unavailable; a substitution may have occurred.

exception wand.exceptions.WandError

Bases: wand.exceptions.BaseError

There was a problem specific to the MagickWand API.

exception wand.exceptions.WandException

Bases: exceptions.Exception

All Wand-related exceptions are derived from this class.

exception wand.exceptions.WandFatalError

Bases: wand.exceptions.BaseFatalError

There was a problem specific to the MagickWand API.

exception wand.exceptions.WandLibraryVersionError

Bases: wand.exceptions.WandException

Base class for Wand-related ImageMagick version errors.

New in version 0.3.2.

exception wand.exceptions.WandWarning

Bases: wand.exceptions.BaseWarning

There was a problem specific to the MagickWand API.

exception wand.exceptions.XServerError

Bases: wand.exceptions.BaseError

An X resource is unavailable.

exception wand.exceptions.XServerFatalError

Bases: wand.exceptions.BaseFatalError

An X resource is unavailable.

exception wand.exceptions.XServerWarning

Bases: wand.exceptions.BaseWarning

An X resource is unavailable.

wand.api — Low-level interfaces

Changed in version 0.1.10: Changed to throw ImportError instead of AttributeError when the shared library fails to load.

class wand.api.MagickPixelPacket
class wand.api.PointInfo
class wand.api.AffineMatrix
class wand.api.c_magick_char_p

This subclass prevents the automatic conversion behavior of ctypes.c_char_p, allowing memory to be properly freed in the destructor. It must only be used for non-const character pointers returned by ImageMagick functions.

wand.api.library

(ctypes.CDLL) The MagickWand library.

wand.api.libc

(ctypes.CDLL) The C standard library.

wand.api.libmagick

(ctypes.CDLL) The ImageMagick library. It is the same with library on platforms other than Windows.

New in version 0.1.10.

wand.api.load_library()

Loads the MagickWand library.

Returns:the MagickWand library and the ImageMagick library
Return type:ctypes.CDLL

wand.compat — Compatibility layer

This module provides several subtle things to support multiple Python versions (2.6, 2.7, 3.2–3.5) and VM implementations (CPython, PyPy).

wand.compat.PY3 = False

(bool) Whether it is Python 3.x or not.

wand.compat.binary(string, var=None)

Makes string to str in Python 2. Makes string to bytes in Python 3.

Parameters:
  • string (bytes, str, unicode) – a string to cast it to binary_type
  • var (str) – an optional variable name to be used for error message
wand.compat.binary_type

alias of __builtin__.str

wand.compat.encode_filename(filename)

If filename is a text_type, encode it to binary_type according to filesystem’s default encoding.

wand.compat.file_types = (<class 'io.RawIOBase'>, <type 'file'>)

(type, tuple) Types for file objects that have fileno().

wand.compat.nested(*args, **kwds)

Combine multiple context managers into a single nested context manager.

This function has been deprecated in favour of the multiple manager form of the with statement.

The one advantage of this function over the multiple manager form of the with statement is that argument unpacking allows it to be used with a variable number of context managers as follows:

with nested(*managers):
do_something()
wand.compat.string_type

alias of __builtin__.basestring

wand.compat.text(string)

Makes string to str in Python 3. Does nothing in Python 2.

Parameters:string (bytes, str, unicode) – a string to cast it to text_type
wand.compat.text_type

alias of __builtin__.unicode

class wand.compat.xrange(stop) → xrange object

xrange(start, stop[, step]) -> xrange object

Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient.

wand.display — Displaying images

The display() functions shows you the image. It is useful for debugging.

If you are in Mac, the image will be opened by your default image application (Preview.app usually).

If you are in Windows, the image will be opened by imdisplay.exe, or your default image application (Windows Photo Viewer usually) if imdisplay.exe is unavailable.

You can use it from CLI also. Execute wand.display module through python -m option:

$ python -m wand.display wandtests/assets/mona-lisa.jpg

New in version 0.1.9.

wand.display.display(image, server_name=':0')

Displays the passed image.

Parameters:
  • image (Image) – an image to display
  • server_name (str) – X11 server name to use. it is ignored and not used for Mac. default is ':0'

wand.version — Version data

You can find the current version in the command line interface:

$ python -m wand.version
0.4.5
$ python -m wand.version --verbose
Wand 0.4.5
ImageMagick 6.7.7-6 2012-06-03 Q16 http://www.imagemagick.org
$ python -m wand.version --config | grep CC | cut -d : -f 2
gcc -std=gnu99 -std=gnu99
$ python -m wand.version --fonts | grep Helvetica
Helvetica
Helvetica-Bold
Helvetica-Light
Helvetica-Narrow
Helvetica-Oblique
$ python -m wand.version --formats | grep CMYK
CMYK
CMYKA

New in version 0.2.0: The command line interface.

New in version 0.2.2: The --verbose/-v option which also prints ImageMagick library version for CLI.

New in version 0.4.1: The --fonts, --formats, & --config option allows printing additional information about ImageMagick library.

wand.version.VERSION = '0.4.5'

(basestring) The version string e.g. '0.1.2'.

Changed in version 0.1.9: Becomes string. (It was tuple before.)

wand.version.VERSION_INFO = (0, 4, 5)

(tuple) The version tuple e.g. (0, 1, 2).

Changed in version 0.1.9: Becomes tuple. (It was string before.)

wand.version.MAGICK_VERSION = None

(basestring) The version string of the linked ImageMagick library. The exactly same string to the result of GetMagickVersion() function.

Example:

'ImageMagick 6.7.7-6 2012-06-03 Q16 http://www.imagemagick.org'

New in version 0.2.1.

wand.version.MAGICK_VERSION_INFO = None

(tuple) The version tuple e.g. (6, 7, 7, 6) of MAGICK_VERSION.

New in version 0.2.1.

wand.version.MAGICK_VERSION_NUMBER = None

(numbers.Integral) The version number of the linked ImageMagick library.

New in version 0.2.1.

wand.version.MAGICK_RELEASE_DATE = None

(datetime.date) The release date of the linked ImageMagick library. Equivalent to the result of GetMagickReleaseDate() function.

New in version 0.2.1.

wand.version.MAGICK_RELEASE_DATE_STRING = None

(basestring) The date string e.g. '2012-06-03' of MAGICK_RELEASE_DATE_STRING. This value is the exactly same string to the result of GetMagickReleaseDate() function.

New in version 0.2.1.

wand.version.QUANTUM_DEPTH = None

(numbers.Integral) The quantum depth configuration of the linked ImageMagick library. One of 8, 16, 32, or 64.

New in version 0.3.0.

wand.version.configure_options(pattern='*')

Queries ImageMagick library for configurations options given at compile-time.

Example: Find where the ImageMagick documents are installed:

>>> from wand.version import configure_options
>>> configure_options('DOC*')
{'DOCUMENTATION_PATH': '/usr/local/share/doc/ImageMagick-6'}
Parameters:pattern (basestring) – A term to filter queries against. Supports wildcard ‘*’ characters. Default patterns ‘*’ for all options.
Returns:Directory of configuration options matching given pattern
Return type:collections.defaultdict
wand.version.fonts(pattern='*')

Queries ImageMagick library for available fonts.

Available fonts can be configured by defining types.xml, type-ghostscript.xml, or type-windows.xml. Use wand.version.configure_options() to locate system search path, and resources article for defining xml file.

Example: List all bold Helvetica fonts:

>>> from wand.version import fonts
>>> fonts('*Helvetica*Bold*')
['Helvetica-Bold', 'Helvetica-Bold-Oblique', 'Helvetica-BoldOblique',
 'Helvetica-Narrow-Bold', 'Helvetica-Narrow-BoldOblique']
Parameters:pattern (basestring) – A term to filter queries against. Supports wildcard ‘*’ characters. Default patterns ‘*’ for all options.
Returns:Sequence of matching fonts
Return type:collections.Sequence
wand.version.formats(pattern='*')

Queries ImageMagick library for supported formats.

Example: List supported PNG formats:

>>> from wand.version import formats
>>> formats('PNG*')
['PNG', 'PNG00', 'PNG8', 'PNG24', 'PNG32', 'PNG48', 'PNG64']
Parameters:pattern (basestring) – A term to filter formats against. Supports wildcards ‘*’ characters. Default pattern ‘*’ for all formats.
Returns:Sequence of matching formats
Return type:collections.Sequence

Troubleshooting

Mailing list

Wand has the list for users. If you want to subscribe the list, just send a mail to:

The list archive provided by Librelist is synchronized every hour.

Stack Overflow

There’s a Stack Overflow tag for Wand:

http://stackoverflow.com/questions/tagged/wand

Freely ask questions about Wand including troubleshooting. Thanks for sindikat’s contribution.

Quora

There’s a Quora topic for Wand: Wand (ImageMagick binding). Be free to add questions to the topic, though it’s suitable for higher-level questions rather than troubleshooting.

Open source

Wand is an open source software written by Hong Minhee (initially written for StyleShare). See also the complete list of contributors as well. The source code is distributed under MIT license and you can find it at GitHub repository. Check out now:

$ git clone git://github.com/emcconville/wand.git

If you find a bug, please notify to our issue tracker. Pull requests are always welcome!

We discuss about Wand’s development on IRC. Come #wand channel on freenode network.

Check out Wand Changelog also.

Indices and tables