Wand
Wand is a ctypes-based simple ImageMagick binding for Python. It provides a Pythonic interface to the MagickWand API, enabling comprehensive image manipulation tasks such as resizing, cropping, rotating, applying effects, and converting between various image formats. The current version is 0.7.0, and it is actively maintained with regular releases.
Warnings
- breaking Wand 0.7.0 removed support for Python 2. All Python 2 compatibility code has been eliminated.
- gotcha Wand is a binding to the ImageMagick C library and requires ImageMagick to be installed on your system. It does not ship with ImageMagick itself.
- gotcha For some installations (e.g., Homebrew on Apple Silicon macOS, or custom ImageMagick paths on Windows/Linux), you may need to set the `MAGICK_HOME` environment variable to the ImageMagick installation directory for Wand to find it.
- gotcha Failing to use the `with` statement (context manager) with `wand.image.Image` objects, or manually calling `.close()`, can lead to memory leaks, especially in long-running applications.
- gotcha When processing PDFs, Wand defaults to a resolution of 72 DPI. If the original PDF has a higher resolution or if high-quality output is needed, this default can lead to significant quality degradation or unexpected scaling issues.
Install
-
pip install wand
Imports
- Image
from wand.image import Image
Quickstart
import os
from wand.image import Image
# Create a dummy image file for demonstration if it doesn't exist
dummy_image_path = 'example.jpg'
if not os.path.exists(dummy_image_path):
try:
# Using a minimal Pillow to create a dummy image if Wand can't (no ImageMagick installed yet)
from PIL import Image as PImage
PImage.new('RGB', (400, 300), color = 'red').save(dummy_image_path)
print(f"Created a dummy image: {dummy_image_path}")
except ImportError:
print("Please create an 'example.jpg' file or install Pillow (pip install Pillow) to run this quickstart.")
exit()
# Ensure ImageMagick can be found if MAGICK_HOME is needed (e.g., on some macOS/Windows installs)
# os.environ['MAGICK_HOME'] = '/opt/homebrew' # Example for Homebrew on macOS
try:
with Image(filename=dummy_image_path) as img:
print(f"Original size: {img.width}x{img.height}")
# Resize the image to 200x150 pixels
img.resize(200, 150)
output_path = 'resized_example.jpg'
img.save(filename=output_path)
print(f"Resized image saved to {output_path} with size: {img.width}x{img.height}")
# Apply a blur effect
img.blur(radius=0, sigma=3)
blurred_output_path = 'blurred_example.jpg'
img.save(filename=blurred_output_path)
print(f"Blurred image saved to {blurred_output_path}")
except Exception as e:
print(f"An error occurred: {e}")
print("Make sure ImageMagick is installed and correctly configured (e.g., MAGICK_HOME environment variable).")