### Install Wand from Source Source: https://github.com/emcconville/wand/blob/master/README.rst Clone the repository and install Wand from the source code. This is useful for development or to get the latest features. ```console git clone git://github.com/emcconville/wand.git cd wand/ python setup.py install ``` -------------------------------- ### Install Wand with Development Dependencies Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.6.md To install additional development dependencies for documentation and testing, use pip with the `[doc,test]` extra. ```default pip install -U Wand[doc,test] ``` -------------------------------- ### Install Wand using pip Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install the Wand Python library using pip. This is the primary method for installing Wand. ```console $ pip install Wand ``` -------------------------------- ### Install Wand on FreeBSD Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install the py-wand package on FreeBSD systems using the pkg_add command. ```bash $ pkg_add -r py-wand ``` -------------------------------- ### Install Wand using pip Source: https://github.com/emcconville/wand/blob/master/README.rst Use this command to install the Wand library from the Python Package Index. ```console pip install Wand ``` -------------------------------- ### Install Wand and Dependencies Source: https://github.com/emcconville/wand/blob/master/docs/index.md Installs the Wand Python package and its required MagickWand development library using apt-get and pip. ```bash apt-get install libmagickwand-dev pip install Wand ``` -------------------------------- ### Install Wand on Debian/Ubuntu Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install the python-wand package on Debian or Ubuntu systems using the apt-get command. ```bash $ sudo apt-get install python-wand ``` -------------------------------- ### Install Wand on Fedora Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install the python3-wand package on Fedora systems using the dnf command. ```bash $ dnf install python3-wand ``` -------------------------------- ### Install ImageMagick on Fedora/CentOS Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install ImageMagick on Red Hat-based systems like Fedora or CentOS using Yum. Ensure ImageMagick libraries are installed. ```console $ yum update $ yum install ImageMagick-libs ``` -------------------------------- ### Install and Run Tests with Pytest Source: https://github.com/emcconville/wand/blob/master/docs/test.md Manually install pytest and then run Wand's tests directly using the pytest command. This method offers more control and options. ```console $ pip install pytest $ pytest ``` -------------------------------- ### Install Tox Source: https://github.com/emcconville/wand/blob/master/docs/test.md Install the tox testing tool using pip. Tox is used to automate testing across various Python implementations. ```console $ pip install tox ``` -------------------------------- ### Affine 3-Point Distortion Example Source: https://github.com/emcconville/wand/blob/master/docs/guide/distortion.md Shows how to apply `affine` distortion, which requires 6 arguments representing three 2D points. ```default # Affine 3-point will require 6 arguments points = (x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6) img.distort('affine', points) ``` -------------------------------- ### Install Wand on Alpine Linux Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install ImageMagick and Wand on Alpine Linux using apk and pip, respectively. Ensure MAGICK_HOME is set before running Wand applications. ```bash # apk add imagemagick ``` ```bash # pip install Wand ``` ```bash # export MAGICK_HOME=/usr ``` -------------------------------- ### Install ImageMagick with liblqr using Homebrew on Mac Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install ImageMagick with the liblqr library using Homebrew on macOS. This is required for seam carving functionality. ```console $ brew install imagemagick --with-liblqr ``` -------------------------------- ### Install ImageMagick on Debian/Ubuntu Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install ImageMagick on Debian-based systems like Ubuntu using the APT package manager. This is a prerequisite for Wand. ```console $ sudo apt install imagemagick ``` -------------------------------- ### Run Wand Tests with setup.py Source: https://github.com/emcconville/wand/blob/master/docs/test.md Execute the unit and regression tests for Wand using the setup.py script. This command automatically installs pytest if it's not already present. ```console $ python setup.py test ``` -------------------------------- ### Install ImageMagick with Homebrew on Mac Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install ImageMagick on macOS using Homebrew. This command installs the base ImageMagick package. ```console $ brew install imagemagick ``` -------------------------------- ### Image Drawing Setup Source: https://github.com/emcconville/wand/blob/master/docs/guide/draw.md Initializes an image and a drawing context, then calls helper functions to draw a region of interest and set drawing properties like fill color. This sets up the environment for subsequent drawing operations. ```python message = ("""This is some really long sentence with""" """ the word "Mississippi" in it.""" ) ROI_SIDE = 175 with Image(filename='logo:') as img: with Drawing() as ctx: draw_roi(ctx, ROI_SIDE, ROI_SIDE) # Set the font style ctx.fill_color = 'RED' ``` -------------------------------- ### Install ImageMagick with MacPorts on Mac Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install ImageMagick on macOS using MacPorts. This command installs the base ImageMagick package. ```console $ sudo port install imagemagick ``` -------------------------------- ### Example Pytest Configuration Source: https://github.com/emcconville/wand/blob/master/docs/test.md An example pytest.ini file demonstrating common configurations for running nightly regression tests in parallel with coverage reports. It includes options for parallel execution (-n8), reporting (-rsfEw), and code coverage (--cov wand --cov-report html). ```ini [pytest] addopts=-n8 -rsfEw --cov wand --cov-report html ``` -------------------------------- ### Manage Image Profiles (EXIF, ICC, XMP) Source: https://github.com/emcconville/wand/blob/master/docs/guide/exif.md This example demonstrates how to extract, import, and delete image profiles such as EXIF, ICC, and XMP using the `Image.profiles` dictionary. Note that modifying profiles requires re-encoding the image data. ```python with Image(filename='wandtests/assets/beach.jpg') as image: # Extract EXIF payload if 'EXIF' in image.profiles: exif_binary = image.profiles['EXIF'] # Import/replace ICC payload with open('color_profile.icc', 'rb') as icc: image.profiles['ICC'] = icc.read() # Remove XMP payload del image.profiles['XMP'] ``` -------------------------------- ### Emulate PIL Module-Level Import Source: https://github.com/emcconville/wand/blob/master/docs/roadmap.md Use this snippet to provide module-level compatibility with PIL by importing Image from wand.pilcompat. Requires installation of Wand. ```python try: from wand.pilcompat import Image except ImportError: from PIL import Image ``` -------------------------------- ### Install Ghostscript with Homebrew on Mac Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Install Ghostscript using Homebrew on macOS. This is necessary for rendering PDF files and using FreeType font features with ImageMagick. ```console $ brew install ghostscript ``` -------------------------------- ### Get Image as Binary String with Specified Format Source: https://github.com/emcconville/wand/blob/master/docs/guide/write.md You can specify the desired output format directly when calling `make_blob()`. This simplifies the process of getting a binary string in a particular image format. ```default from wand.image import Image with Image(filename='pikachu.png') as img: jpeg_bin = img.make_blob('jpeg') ``` -------------------------------- ### Arc Distortion Example Source: https://github.com/emcconville/wand/blob/master/docs/guide/distortion.md Demonstrates the `arc` distortion method, which requires a minimum of one argument: the degree of the arc. ```default # Arc can have a minimum of 1 argument img.distort('arc', (degree, )) ``` -------------------------------- ### Set MAGICK_HOME on Windows Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Set the MAGICK_HOME environment variable on Windows to the installation path of ImageMagick. This is crucial for Wand to link correctly. ```console C:\Program Files\ImageMagick-6.9.3-Q16 ``` -------------------------------- ### Applying Colors to Montage Components Source: https://github.com/emcconville/wand/blob/master/docs/guide/montage.md Use this snippet to set background, matte, and border colors for montage images. Ensure Wand is installed and imported. ```python from wand.image import Image with Image() as img: for src in ['pattern:crosshatch', 'canvas:orange', 'plasma:']: with Image(width=64, height=64, pseudo=src) as item: item.border_color = 'cyan' # Inner Frame item.matte_color = 'yellow' # Outer Frame img.image_add(item) img.background_color = 'magenta' # Canvas background img.montage(font=style) img.save(filename='montage-color.png') ``` -------------------------------- ### Clone Wand Repository Source: https://github.com/emcconville/wand/blob/master/docs/index.md Clone the Wand project from its GitHub repository to get the source code. ```bash $ git clone git://github.com/emcconville/wand.git ``` -------------------------------- ### Get Image as Binary String (Blob) Source: https://github.com/emcconville/wand/blob/master/docs/guide/write.md Retrieve the binary representation of an image using the `make_blob()` method. This is useful for sending image data over a network or storing it in a database. ```default from wand.image import Image with Image(filename='pikachu.png') as img: img.format = 'jpeg' jpeg_bin = img.make_blob() ``` -------------------------------- ### Run Tox Tests Source: https://github.com/emcconville/wand/blob/master/docs/test.md Execute tox in the Wand directory to test the project against multiple Python interpreters. This command automates the setup and execution of tests for each configured environment. ```console $ tox ``` -------------------------------- ### Apply Sketch Effect Source: https://github.com/emcconville/wand/blob/master/docs/guide/fx.md The sketch() method simulates an artist's sketch drawing. It requires transforming the image to grayscale first. This example uses specific parameters for the sketch effect. ```python from wand.image import Image with Image(filename="inca_tern.jpg") as img: img.transform_colorspace("gray") img.sketch(0.5, 0.0, 98.0) img.save(filename="fx-sketch.jpg") ``` -------------------------------- ### Affine Projection Distortion Example Source: https://github.com/emcconville/wand/blob/master/docs/guide/distortion.md Applies an 'affine_projection' distortion, which requires exactly 6 real numbers representing scale, rotate, and translate parameters. Uses 'skyblue' background and 'background' virtual pixels. ```python from collections import namedtuple from wand.color import Color from wand.image import Image Point = namedtuple('Point', ['x', 'y']) with Image(filename='rose:') as img: img.resize(140, 92) img.background_color = Color('skyblue') img.virtual_pixel = 'background' rotate = Point(0.1, 0) scale = Point(0.7, 0.6) translate = Point(5, 5) args = ( scale.x, rotate.x, rotate.y, scale.y, translate.x, translate.y ) img.distort('affine_projection', args) ``` -------------------------------- ### Draw Points Following a Mathematical Function Source: https://github.com/emcconville/wand/blob/master/docs/guide/draw.md Use the `point()` method to draw individual points on an image. This example plots points based on the tangent function. Ensure `wand.drawing.Drawing` and `math` are imported. ```default from wand.image import Image from wand.drawing import Drawing from wand.color import Color import math with Drawing() as draw: for x in range(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) ``` -------------------------------- ### Explicitly link to ImageMagick using MAGICK_HOME Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Specify the path to your ImageMagick installation by setting the MAGICK_HOME environment variable. Wand uses this variable to find the correct ImageMagick libraries. ```console export MAGICK_HOME=/path/to/ImageMagick ``` -------------------------------- ### Create Binary Image from Bytes Source: https://github.com/emcconville/wand/blob/master/docs/guide/morphology.md Generates a PBM image from a byte string literal for use in morphology examples. Ensure the image is saved to a file for subsequent operations. ```python pbm = b"""P1 10 10 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0 1 1 1 1 1 0 1 1 0 0 0 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 1 0 1 0 1 0 1 1 1 1 1 0 1 0 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 """ with Image(blob=pbm, format="PBM") as img: img.sample(100, 100) img.save(filename="morph-src.png") ``` -------------------------------- ### Apply Color Threshold to Image Source: https://github.com/emcconville/wand/blob/master/docs/guide/threshold.md Creates a binary image by forcing pixels within a specified range (start to stop) to white, and others to black. Requires ImageMagick-7.0.10. ```python from wand.image import Image with Image(filename='inca_tern.jpg') as img: img.color_threshold(start='#333', stop='#cdc') img.save(filename='threshold_color.jpg') ``` -------------------------------- ### Apply Custom FX Filter Source: https://github.com/emcconville/wand/blob/master/docs/guide/fx.md Use the fx() method to apply custom expressions for image manipulation. This example creates a black and white image, preserving colors with a specific hue range. ```python from wand.image import Image fx_filter="(hue > 0.9 || hue < 0.1) ? u : lightness" with Image(filename="inca_tern.jpg") as img: with img.fx(fx_filter) as filtered_img: filtered_img.save(filename="fx-fx.jpg") ``` -------------------------------- ### Set Resource Limits Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.5.md Define run-time policies for image processing to prevent excessive system resource consumption. This example limits raster operations to a single CPU thread. ```python from wand.image import Image from wand.resource import limits limits['thread'] = 1 # Only allow one CPU thread for raster. with Image(filename='input.tif') as img: pass ``` -------------------------------- ### Evaluate Images by Adding Pixel Values Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.7.md Generate a new image by adding the pixel values of source images using the 'add' operator. This example demonstrates adding two grayscale images. Requires importing Color and Image from wand. ```python >>> from wand.color import Color >>> from wand.image import Image >>> >>> S=dict(width=1, height=1) >>> with Image() as src: ... # Read 50% & 25% gray images. ... src.read(pseudo='xc:gray50', **S) ... src.read(pseudo='xc:gray25', **S) ... # Create a new image by adding pixel values. ... # ( 50% + 25% = 75% ) ... with src.evaluate_images(operator='add') as dst: ... assert dst[0, 0] == Color('gray75') ``` -------------------------------- ### Sample Image for Speed Source: https://github.com/emcconville/wand/blob/master/docs/guide/resizecrop.md Use the `sample` method for faster resizing when speed is critical. It works similarly to `resize` but does not support filter or blur options. ```python >>> img.sample(50, 60) >>> img.size (50, 60) ``` -------------------------------- ### Set MAGICK_HOME for MacPorts Python on Mac Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Set the MAGICK_HOME environment variable when Python is not installed using MacPorts. This ensures Wand can find the ImageMagick installation. ```console $ export MAGICK_HOME=/opt/local ``` -------------------------------- ### Open an image file by filename Source: https://github.com/emcconville/wand/blob/master/docs/guide/read.md Use the Image constructor with the 'filename' keyword argument to open an image directly from a file path. Ensure the argument is passed as a keyword. ```python from wand.image import Image with Image(filename='pikachu.png') as img: print('width =', img.width) print('height =', img.height) ``` -------------------------------- ### Iterate Forward Through Image Sequence Source: https://github.com/emcconville/wand/blob/master/docs/guide/sequence.md Use iterator_reset() and iterator_next() to loop through all frames of an image sequence from start to end. Ensure to reset the iterator before starting the loop. ```python >>> with Image(filename='link_to_the_past.gif') as img: ... img.iterator_reset() ... print("First frame", img.size) ... while img.iterator_next(): ... print("Additional frame", img.size) First frame (300, 289) Additional frame (172, 128) Additional frame (172, 145) Additional frame (123, 112) Additional frame (144, 182) Additional frame (107, 117) Additional frame (171, 128) Additional frame (123, 107) ``` -------------------------------- ### Create Default Montage Source: https://github.com/emcconville/wand/blob/master/docs/guide/montage.md Generates a montage of images using default settings. Images are added to a stack and then montaged. ```python from wand.image import Image with Image() as img: for src in ['pattern:crosshatch', 'netscape:', 'plasma:']: with Image(width=64, height=64, pseudo=src) as item: img.image_add(item) img.montage() img.border('magenta', 2, 2) img.save(filename='montage-default.png') ``` -------------------------------- ### Iterate Backward Through Image Sequence Source: https://github.com/emcconville/wand/blob/master/docs/guide/sequence.md Use iterator_last() and iterator_previous() to loop through all frames of an image sequence from end to start. Ensure to move to the last frame before starting the backward iteration. ```python >>> with Image(filename='link_to_the_past.gif') as img: ... img.iterator_last() ... print("End frame", img.size) ... while img.iterator_previous(): ... print("Previous frame", img.size) End frame (123, 107) Previous frame (171, 128) Previous frame (107, 117) Previous frame (144, 182) Previous frame (123, 112) Previous frame (172, 145) Previous frame (172, 128) Previous frame (300, 289) ``` -------------------------------- ### Proper Memory Management with Image Context Manager Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.6.md It is recommended to use Wand's `Image` class within a `with` statement to ensure proper memory and resource deallocation. This guarantees that resources are released even if errors occur. ```default with Image(filename='input.jpg') as img: pass ``` -------------------------------- ### Get Image Palette using Histogram Keys Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.3.md Access the `histogram` attribute of an image to retrieve a dictionary-like object of colors and their pixel counts. Get the palette by calling `.keys()` on the histogram. ```pycon >>> url = 'http://farm7.staticflickr.com/6145/5982384872_cb1e01004e_n.jpg' >>> with Image(file=urllib2.urlopen(url)) as image: ... palette = image.histogram.keys() ``` -------------------------------- ### Open an empty image with specified dimensions Source: https://github.com/emcconville/wand/blob/master/docs/guide/read.md Create a new, empty image by providing 'width' and 'height' keyword arguments to the Image constructor. The default background is transparent. This functionality was added in version 0.2.2. ```python from wand.image import Image with Image(width=200, height=100) as img: img.save(filename='200x100-transparent.png') ``` -------------------------------- ### Get Image Colorspace Type Source: https://github.com/emcconville/wand/blob/master/docs/guide/colorspace.md Check the colorspace type of an image. The available types depend on the image format. ```python >>> 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' ``` -------------------------------- ### Resize, Crop, and Liquid Rescale Images with Wand Source: https://github.com/emcconville/wand/blob/master/docs/guide/resizecrop.md Demonstrates resizing, cropping, and liquid rescaling of an image using Wand. Ensure the 'seam.jpg' image is available in the same directory. This method is useful for maintaining image aspect ratio while changing dimensions. ```python >>> 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) ``` -------------------------------- ### Get Number of Frames in Sequence Source: https://github.com/emcconville/wand/blob/master/docs/guide/sequence.md Use len() on the image sequence to determine the total number of frames in an animated image. ```python from wand.image import Image with Image(filename='sequence-animation.gif') as image: len(image.sequence) ``` -------------------------------- ### Create Symbolic Links for ImageMagick Libraries on Alpine Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Create symbolic links for ImageMagick libraries on Alpine Linux if they are not automatically recognized by Wand. This ensures Wand can locate the necessary shared libraries. ```bash # ln -s /usr/lib/libMagickCore-7.Q16HDRI.so.9 /usr/lib/libMagickCore-7.Q16HDRI.so ``` ```bash # ln -s /usr/lib/libMagickWand-7.Q16HDRI.so.9 /usr/lib/libMagickWand-7.Q16HDRI.so ``` -------------------------------- ### Manage Image Resource with `with` Statement Source: https://github.com/emcconville/wand/blob/master/docs/guide/resource.md Use a `with` statement for automatic resource management of Image objects. This ensures the resource is properly closed after use. ```python with Image(filename='') as img: # deal with img... ``` -------------------------------- ### Draw a Partial Ellipse Source: https://github.com/emcconville/wand/blob/master/docs/guide/draw.md Draws a segment of an ellipse by providing start and end degrees. This allows for creating arcs or partial shapes. ```python draw.ellipse((50, 50), # Origin (center) point (40, 20), # 80px wide, and 40px tall (90,-90)) # Draw half of ellipse from bottom to top ``` -------------------------------- ### Get Image Format Source: https://github.com/emcconville/wand/blob/master/docs/guide/write.md Check the current format of an image object using the `format` property. This property is also writable to convert the image. ```pycon >>> image.format 'JPEG' ``` -------------------------------- ### Create a Basic Dot Image for Morphology Source: https://github.com/emcconville/wand/blob/master/docs/guide/morphology.md Generates a simple white dot on a black background, which serves as a base image for demonstrating morphology operations. ```python from wand.image import Image with Image(width=1, height=1, pseudo='xc:white') as img: img.border('black', 6, 6, compose='copy') img.save(filename='morph-dot.png') ``` -------------------------------- ### Get Image Dimensions Source: https://github.com/emcconville/wand/blob/master/docs/guide/resizecrop.md Retrieve the current width and height of an image using the `width` and `height` properties. The `size` property provides both dimensions as a tuple. ```python >>> 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 ``` ```python >>> img.size (500, 600) ``` -------------------------------- ### Load, Resize, Rotate, and Save Image with Wand Source: https://github.com/emcconville/wand/blob/master/docs/index.md This snippet demonstrates loading an image, resizing it by a factor, rotating it, saving modified versions, and displaying them. Ensure 'mona-lisa.png' exists in the same directory. ```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) ``` -------------------------------- ### Transform Colors with a Matrix Source: https://github.com/emcconville/wand/blob/master/docs/guide/fx.md Recalculates color values by applying a matrix transform. The matrix can be up to a 6x6 grid. This example swaps the Red and Blue channels. ```python from wand.image import Image with Image(filename="inca_tern.jpg") as img: matrix = [[0, 0, 1], [0, 1, 0], [1, 0, 0]] img.color_matrix(matrix) img.save(filename="fx-color-matrix.jpg") ``` -------------------------------- ### Read a Range of Frames Source: https://github.com/emcconville/wand/blob/master/docs/guide/read.md Load a specific range of frames from an animated image format like GIF by providing the start and end frame indices in the filename. ```python with Image(filename='animation.gif[0-11]') as first_dozen: pass ``` -------------------------------- ### Draw a Complex Path with Curves and Lines Source: https://github.com/emcconville/wand/blob/master/docs/guide/draw.md Use `path_start()` and `path_finish()` to define a path composed of curves and lines. Control points and relative positioning are demonstrated. Ensure `wand.drawing.Drawing` is imported. ```default 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 across top-left to center draw.path_curve(to=(40, 0), controls=[(10, -40), (30,-40)], relative=True) # Continue curve across 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) ``` -------------------------------- ### Read an image from an input stream Source: https://github.com/emcconville/wand/blob/master/docs/guide/read.md When an image is available as a file-like object (e.g., from urlopen or StringIO), use the 'file' keyword argument in the Image constructor. The object must implement a 'read()' method. ```python 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() ``` -------------------------------- ### Initialize Drawing Object Source: https://github.com/emcconville/wand/blob/master/docs/guide/draw.md Instantiate a Drawing object to buffer drawing instructions. It can be called with an Image object to apply the buffered instructions. ```python 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) ``` -------------------------------- ### Skip FFT Tests with Pytest Source: https://github.com/emcconville/wand/blob/master/docs/test.md Utilize the --skip-fft option to skip test cases involving discrete Fourier transformations, particularly when the Fourier Transform library is not installed. ```console $ pytest --skip-fft ``` -------------------------------- ### Perspective Distortion with Matte Color and Tiled Virtual Pixels Source: https://github.com/emcconville/wand/blob/master/docs/guide/distortion.md Applies a 'perspective' distortion, setting the matte color to 'ORANGE' and using 'tile' for virtual pixels. This requires 12 arguments for the perspective transformation. ```python from wand.color import Color from wand.image import Image with Image(filename='rose:') as img: img.resize(140, 92) img.matte_color = Color('ORANGE') img.virtual_pixel = 'tile' args = (0, 0, 30, 60, 140, 0, 110, 60, 0, 92, 2, 90, 140, 92, 138, 90) img.distort('perspective', args) ``` -------------------------------- ### Basic Distortion Method Signature Source: https://github.com/emcconville/wand/blob/master/docs/guide/distortion.md Illustrates the basic function signature for applying distortions using `Image.distort` with a method and arguments. ```default with Image(...) as img: img.distort(method, arguments) ``` -------------------------------- ### Create Stereogram Source: https://github.com/emcconville/wand/blob/master/docs/guide/fx.md The stereogram() class method generates a 3D image by combining two images (left and right eye views). This example creates a stereogram from 'left_camera.jpg' and 'right_camera.jpg'. ```python from wand.image import Image with Image(filename="left_camera.jpg") as left_eye: with Image(filename="right_camera.jpg") as right_eye: with Image.stereogram(left=left_eye, right=right_eye) as img: img.save(filename="fx-stereogram.jpg") ``` -------------------------------- ### Seed Kmeans Quantization with Custom Colors Source: https://github.com/emcconville/wand/blob/master/docs/guide/quantize.md Provide a semicolon-delimited list of colors to seed the initial color selection for the `kmeans` quantization. This can influence the resulting color palette. Requires ImageMagick-7.0.10-37. ```python from wand.image import Image with Image(filename='hummingbird.jpg') as img: img.artifacts['kmeans:seed-colors'] = 'teal;#586f5f;#4d545c;#617284' img.kmeans(number_colors=32, max_iterations=100, tolerance=0.01) img.save(filename='quantize_kmeans_seed.jpg') ``` -------------------------------- ### Extract Meta Channel with Channel FX Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.7.md Use Channel FX to extract a meta channel from a PSD file and save it as a new image. Requires importing Image from wand.image. ```python >>> from wand.image import Image >>> >>> with Image(filename='tagged_image.psd') as img: ... with img.channel_fx('meta') as meta: ... meta.save(filename='meta_channel.png') ``` -------------------------------- ### Apply Implode Effect Source: https://github.com/emcconville/wand/blob/master/docs/guide/fx.md The implode() method pulls pixels towards the center of the image. The amount argument controls the range of pixels affected. This example applies an implode effect with an amount of 0.35. ```python from wand.image import Image with Image(filename="inca_tern.jpg") as img: img.implode(amount=0.35) img.save(filename="fx-implode.jpg") ``` -------------------------------- ### Configure ImageMagick Resource Limits Source: https://github.com/emcconville/wand/blob/master/docs/guide/security.md Update policy.xml to set resource limits for memory, map, width, height, area, disk, file, thread, throttle, and time. This helps prevent denial-of-service attacks. ```xml ``` -------------------------------- ### Read EXIF metadata from an image Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.3.md Access EXIF metadata from an image using the `metadata` property, which returns a dictionary-like object. Filters and prints keys starting with 'exif:'. Requires `urllib2` for fetching the image. ```python >>> url = 'http://farm9.staticflickr.com/8282/7874109806_3fe0080ae4_o_d.jpg' >>> with Image(file=urllib2.urlopen(url)) as i: ... for key, value in i.metadata.items(): ... if key.startswith('exif:'): ... print(key, value) ... ``` -------------------------------- ### Convert image format using convert() Source: https://github.com/emcconville/wand/blob/master/docs/guide/read.md An alternative to cloning for format conversion is the convert() method, which returns a new image object with the specified format. This is a safe method for transformations. ```python from wand.image import Image with Image(filename='pikachu.png') as original: with original.convert('png') as converted: # operations on a converted image... ``` -------------------------------- ### Composite Channel Image with Overlay Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.3.md Use `composite_channel` to overlay an image with a specified channel and operator. Requires downloading an image and creating a background color bar. ```default import shutil import urllib2 from wand.image import Image from wand.color import Color url = 'http://farm6.staticflickr.com/5271/5836279075_c3f8226bc1_z.jpg' with open('composite-channel.jpg', 'wb') as f: u = urllib2.urlopen(url) shutil.copyfileobj(u, f) u.close() with Image(filename='composite-channel.jpg') as image: with Image(background=Color('black'), width=image.width, height=image.height / 3) as bar: image.composite_channel( channel='all_channels', image=bar, operator='overlay', left=0, top=(image.height- bar.height) / 2 ) image.save(filename='composite-channel-result.jpg') ``` -------------------------------- ### Draw Bezier Curve Source: https://github.com/emcconville/wand/blob/master/docs/guide/draw.md Draws a Bezier curve using the bezier() method. Requires a list of at least four (x, y) coordinates for start, end, and control points. Stroke color and width can be customized. ```python 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) ``` -------------------------------- ### Apply Frame to Montage Thumbnails Source: https://github.com/emcconville/wand/blob/master/docs/guide/montage.md Adds a decorative frame around each thumbnail using 'mode="frame"' and 'frame=geometry'. ```python from wand.image import Image with Image() as img: for src in ['pattern:crosshatch', 'canvas:orange', 'plasma:']: with Image(width=64, height=64, pseudo=src) as item: img.image_add(item) img.montage(mode='frame', frame='5') img.border('magenta', 2, 2) img.save(filename='montage-frame.png') ``` -------------------------------- ### Open an empty image with a background color Source: https://github.com/emcconville/wand/blob/master/docs/guide/read.md When creating an empty image, you can specify a background color using the 'background' keyword argument, passing a wand.color.Color object. This feature was added in version 0.2.2. ```python 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') ``` -------------------------------- ### Set MAGICK_HOME for Apple Silicon on Mac Source: https://github.com/emcconville/wand/blob/master/docs/guide/install.md Set the MAGICK_HOME environment variable for Macs with Apple Silicon. This is required before using Wand. ```console $ export MAGICK_HOME=/opt/homebrew ``` -------------------------------- ### Apply Custom Kernel Morphology Source: https://github.com/emcconville/wand/blob/master/docs/guide/morphology.md Demonstrates applying a custom-defined morphology kernel to an image. This allows for highly specific shape transformations. ```python custom_kernel = """ 5x5: -,-,1,-,- -,1,1,1,- -,-,-,-,- -,1,-,1,- 1,1,1,1,1 """ with Image(filename='morph-dot.png') as img: img.morphology(method='dilate', kernel=custom_kernel) img.sample(width=60, height=60) img.save(filename='morph-kernel-custom.png') ``` -------------------------------- ### Apply Sepia Tone Effect Source: https://github.com/emcconville/wand/blob/master/docs/guide/fx.md The sepia_tone() method simulates the effect of old-style sepia toning in photography. The threshold argument controls the intensity of the effect. ```python from wand.image import Image with Image(filename="inca_tern.jpg") as img: img.sepia_tone(threshold=0.8) img.save(filename="fx-sepia-tone.jpg") ``` -------------------------------- ### Apply Multi-Argument Function to Pixel Channels Source: https://github.com/emcconville/wand/blob/master/docs/guide/colorenhancement.md Use the 'function()' method to apply complex multi-argument formulas to pixel channels. Requires importing 'wand.image'. ```python 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]) ``` -------------------------------- ### Apply Top Hat Morphology Source: https://github.com/emcconville/wand/blob/master/docs/guide/morphology.md Applies the 'open' morphology method and returns only the pixels matched by the kernel. Uses an 'octagon' kernel and saves to 'morph-tophat.png'. ```python with Image(filename='morph-src.png') as img: img.morphology(method='tophat', kernel='octagon') img.save(filename='morph-tophat.png') ``` -------------------------------- ### Isolate Image Channels with MagickSetImageChannelMask Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.5.md Demonstrates how to isolate specific color channels (Red & Green) using `MagickSetImageChannelMask` and apply an operation. Restores the previous channel mask afterward. Requires ImageMagick 7 or later. ```default from wand.image import Image, CHANNELS from wand.api import library with Image(filename="rose:") as img: # Isolate only Red & Green channels active_mask = CHANNELS["red"] | CHANNELS["green"] previous_mask = library.MagickSetImageChannelMask(img.wand, active_mask) img.evaluate("rightshift", 1) # Restore previous channels library.MagickSetImageChannelMask(img.wand, previous_mask) img.save(filename="blue_rose.png") ``` -------------------------------- ### Flop Image Horizontally Source: https://github.com/emcconville/wand/blob/master/docs/guide/transform.md Creates a horizontally mirrored image using the `flop()` method. Requires importing 'wand.image'. ```python 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') ``` -------------------------------- ### ImageMagick Version Comparison: Clamping Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.5.md Illustrates how to use the `Image.clamp()` method to prevent color value underflow or overflow after arithmetic operations, ensuring values remain within the valid range, particularly relevant when migrating from ImageMagick-6 to ImageMagick-7. ```default with Image(width=1, height=1, background=Color("gray5")) as canvas: canvas.evaluate("subtract", canvas.quantum_range * 0.07) canvas.clamp() print(canvas[0, 0]) #=> srgb(0,0,0) ``` -------------------------------- ### ImageMagick Version Comparison: Underflow Source: https://github.com/emcconville/wand/blob/master/docs/whatsnew/0.5.md Demonstrates the difference in color value handling between ImageMagick-6 and ImageMagick-7 when performing arithmetic operations that could lead to underflow. ImageMagick-7 may produce negative color values. ```default # ImageMagick-6 with Image(width=1, height=1, background=Color("gray5")) as canvas: canvas.evaluate("subtract", canvas.quantum_range * 0.07) print(canvas[0, 0]) #=> srgb(0,0,0) # ImageMagick-7 with Image(width=1, height=1, background=Color("gray5")) as canvas: canvas.evaluate("subtract", canvas.quantum_range * 0.07) print(canvas[0, 0]) #=> srgb(-1.90207%,-1.90207%,-1.90207%) ``` -------------------------------- ### Explicitly Manage Image Resource with `destroy()` Source: https://github.com/emcconville/wand/blob/master/docs/guide/resource.md Manually manage Image resources by calling the `destroy()` method within a `try...finally` block. This guarantees the resource is cleaned up even if errors occur. ```python try: img = Image(filename='') # deal with img... finally: img.destroy() ```