v7.1.2-36 Latest Stable Release

The FX Special Effects Image Operator

Explore ImageMagick’s FX special effects operator, a powerful pixel-level expression language for image manipulation. Learn how to apply mathematical formulas to transform, distort, composite, and analyze images with flexible scripting examples and advanced functions.

quickstart.sh
# Install via your favorite Package Manager
$ apt install imagemagick
# Convert PNG to WebP with compression
$ magick input.png -quality 85 output.webp
# Resize image maintaining aspect ratio
$ magick input.jpg -resize 800x600^ output.jpg

The FX special effects image operator applies mathematical expressions to each pixel channel of an image. The FX expression language provides a flexible mechanism for fine-grained pixel-level transformations, analysis, and procedural generation.

Procedural Generation

Create procedural canvases, gradients, and mathematical colormaps from equations.

Geometric Distortion

Translate, flip, mirror, rotate, scale, shear, and warp images using custom coordinate functions.

Compositing & Routing

Move color values between images and channels, convolve neighboring pixels, and merge multiple inputs.

Image Metrics

Compute statistical metrics, evaluate properties, and generate custom image "fingerprints."

Examples & Scripting Workflows

1. Simple Channel Modification (Canvas Color Swap)

Convert a black canvas to navy blue by assigning a fixed fractional value to the blue channel:

$ magick -size 64x64 canvas:black -channel blue -fx "1/2" fx_navy.png
Black canvas input
Input
Navy canvas output
Output
2. Non-linear Sigmoidal Contrast Transfer Function

Apply an exponential contrast curve formula to produce a high-contrast version of the source image:

$ magick rose: \
  -fx "(1.0/(1.0+exp(10.0*(0.5-u)))-0.006693)*1.0092503" \
  rose-sigmoidal.png
Rose original
Original
Rose high contrast
High Contrast
3. Variable Assignments & Radial Gradients

Variable assignments (Xi, Yj) reduce expression complexity and enable multi-step calculations such as constructing a radial gradient:

$ magick -size 70x70 canvas: \
  -fx "Xi=i-w/2; Yj=j-h/2; 1.2*(0.5-hypot(Xi,Yj)/70.0)+0.5" \
  radial-gradient.png
Radial gradient
Generated Pattern

Inject Box-Muller Gaussian random noise scaled per color channel:

$ magick photo.jpg -fx 'iso=32; rone=rand(); rtwo=rand(); \
  myn=sqrt(-2*ln(rone))*cos(2*Pi*rtwo); myntwo=sqrt(-2*ln(rtwo))* \
  cos(2*Pi*rone); pnoise=sqrt(p)*myn*sqrt(iso)* \
  channel(4.28,3.86,6.68)/255; max(0,p+pnoise)' noisy.png

Use an iterative for() loop to render a Julia set fractal and map escape iterations through a color lookup table (-clut):

$ magick -size 400x400 xc:gray -fx " \
  Xi=2.4*i/w-1.2; \
  Yj=2.4*j/h-1.2; \
  for (pixel=0.0, (hypot(Xi,Yj) < 2.0) && (pixel < 1.0), \
    delta=Xi^2-Yj^2; \
    Yj=2.0*Xi*Yj+0.2; \
    Xi=delta+0.4; \
    pixel+=0.00390625 \
  ); \
  pixel == 1.0 ? 0.0 : pixel" \
  \( -size 1x1 xc:white xc:red xc:orange xc:yellow xc:green1 xc:cyan xc:blue \
     xc:blueviolet xc:white -reverse +append -filter Cubic -resize 1024x1! \) \
  -clut -rotate -90 julia-set.png
Julia Fractals

Print the first 10 prime numbers to standard output using nested for() loops and debug():

$ magick xc:gray -fx " \
  for (prime=2, prime < 30, composite=0; \
    for (nn=2, nn < (prime/2+1), if ((prime % nn) == 0, composite++, ); nn++); \
      if (composite <= 0, debug(prime), ); prime++)" null:

For more script examples, visit Using FX, The Special Effects Image Operator.

The Anatomy of an FX Expression

Formal building blocks recognized by the FX expression parser:

Element Specification & Examples
Numbers Integers, floating-point values, scientific notation (explicit +/- required on exponent, e.g., 3.81469e-06), and International System / IEC postfixes (KB, MiB, GB, etc.).
Color Names Named ImageMagick colors such as red, green, blue, cyan, black.
Color Hex Values 3-, 6-, or 8-digit hexadecimal color specifications such as #ccc, #cbfed0, or #b9e1cc00.
Color Functions srgb(), srgba(), rgb(), rgba(), cmyk(), cmyka(), hsl(), hsla(), etc.
Channel Constructor channel(...) accepts 0 to 5 arguments and returns the value matching the channel currently being processed (in order RGBKA or CMYKA), zeroing omitted trailing channels (e.g., channel(0.1) sets the first channel to 0.1 and others to 0).
Array Storage An image acts as 2D array storage bounded by its width and height (e.g., p[-1,-1].r), and an image sequence provides multiple arrays (e.g., u.p[0,0].r, v.p[0,0].r). Storage precision is Quantum-limited ([0..65535] for Q16) or floating-point on HDRI-enabled builds.
User Settings Define reusable FX symbols via image options, e.g.:
$ magick ... -set option:wd1 "%[fx:w/2]" -resize "%[fx:wd1-5]" ...
Symbol Description
u, vFirst (u) and second (v) images in the sequence list.
s, t, nCurrent image in list (s; equals u outside %[fx:]), current image index (t), and total image count (n).
i, j, pColumn offset (i), row offset (j), and pixel accessor (p, absolute or relative to current pixel).
w, h, zImage width (w), height (h), and channel depth (z).
r, g, b, a, oRed, green, blue, alpha, and opacity values (from RGBA) of a specific or current pixel.
c, m, y, kCyan, magenta, yellow, and black values of a CMYK pixel.
all, thisChannel specifiers targeting all channels (all) or the active channel being processed (this).
intensityPixel intensity, respecting the -intensity setting.
hue, saturationPixel hue and saturation components.
lightnessPixel lightness: 0.5*max(red,green,blue) + 0.5*min(red,green,blue).
luma, luminancePixel luma / luminance: 0.212656*red + 0.715158*green + 0.072186*blue.
page.width, page.height, page.x, page.yVirtual canvas page dimensions and x/y offsets.
printsize.x, printsize.yHorizontal and vertical print size.
resolution.x, resolution.yHorizontal and vertical image resolution.
depth, extentImage bit depth and file extent.
minima, maxima, mean, medianWhole-image statistics. Append a channel specifier for per-channel stats (e.g., depth.r, mean.this, mean.all).
standard_deviation, kurtosis, skewnessStatistical dispersion, kurtosis, and skewness across the image or a specified channel.
s.depth, s.kurtosis, s.maxima, s.mean, s.median, s.minima, s.resolution.x, s.resolution.y, s.skewness, s.standard_deviationImage attributes prefixed by image reference (s., u., v., or image.).
Constant Value / Description
E, eEuler's number (2.7182818...)
Epsilon, epsilonFloating-point comparison tolerance (1.0 × 10⁻¹²)
OpaqueFull opacity constant (1.0)
PHI, phiGolden ratio (1.6180339...)
PI, Pi, piArchimedes' constant π (3.14159265359...)
QuantumRange, quantumrangeMaximum pixel channel value for the build depth (255 for Q8, 65535 for Q16)
QuantumScale, quantumscaleReciprocal of QuantumRange (1.0 / QuantumRange)
TransparentFull transparency constant (0.0)

Complete reference of built-in mathematical, utility, and control-flow functions:

Function Description & Formula
abs(x)Absolute value of x.
acos(x), acosh(x)Arc cosine and inverse hyperbolic cosine of x.
airy(x)Airy function (max=1, min=0): [jinc(x)]² = [2*j1(pi*x)/(pi*x)]².
alt(x)Sign alternation: returns 1.0 if int(x) is even, -1.0 if odd.
asin(x), asinh(x)Arc sine and inverse hyperbolic sine of x.
atan(x), atanh(x)Arc tangent and inverse hyperbolic tangent of x.
atan2(y, x)Two-argument arc tangent of y/x.
ceil(x)Smallest integral value not less than x.
channel(...)Accepts 0–5 channel expressions; returns the value for the active channel and zeros omitted channels.
clamp(x)Clamps x to the normalized [0.0, 1.0] range.
cos(x), cosh(x)Cosine and hyperbolic cosine of x.
debug(x)Prints x to stderr/stdout for expression debugging (forces single-threaded execution).
do(cond, stmts)Executes stmts, then repeats while cond is non-zero.
drc(x, y)Dynamic range compression (knee curve): x / (y*(x - 1) + 1) for -1 < y < 1.
epoch(date-time)Converts a date-time property into seconds since the Unix epoch (00:00:00 UTC).
erf(x)Gauss error function of x.
exp(x)Natural exponential function (ex).
floor(x)Largest integral value not greater than x.
for(init, cond, stmts)Evaluates init, then iterates stmts while cond is non-zero.
gauss(x)Gaussian function: exp(-x*x/2) / sqrt(2*pi).
gcd(x, y)Greatest common divisor of x and y.
hypot(x, y)Euclidean hypotenuse: sqrt(x² + y²).
if(cond, then, else)Evaluates then if cond is non-zero, otherwise else.
int(x)Greatest integer less than or equal to x.
isnan(x)Returns 1.0 if x is NaN, otherwise 0.0.
j0(x), j1(x)Bessel functions of the first kind of order 0 and order 1.
jinc(x)Jinc function (max=1, min=-0.1323): 2*j1(pi*x)/(pi*x).
ln(x), log(x), logtwo(x)Natural logarithm (base e), base-10 logarithm, and base-2 logarithm.
magicktime()Current system time in seconds since the Unix epoch (00:00:00 UTC).
max(x, y), min(x, y)Maximum or minimum of x and y.
mod(x, y)Floating-point remainder of x divided by y.
not(x)Returns 1.0 if x is zero, otherwise 0.0.
pow(x, y)Power function (xy).
rand()Uniform pseudo-random value in [0.0, 1.0) with a 2¹²⁸ - 1 period.
round(x)Rounds x to the nearest integral value.
sign(x)Returns -1.0 if x < 0.0, otherwise 1.0.
sin(x), sinh(x)Sine and hyperbolic sine of x.
sinc(x)Normalized sinc function (max=1, min=-0.21): sin(pi*x)/(pi*x).
sqrt(x)Square root of x.
squish(x)Logistic sigmoid function: 1.0 / (1.0 + exp(-x)).
tan(x), tanh(x)Tangent and hyperbolic tangent of x.
trunc(x)Truncates x to an integer toward zero.
while(cond, stmts)Iterates stmts while cond is non-zero.
Operator Precedence (Highest to Lowest)
  • 1. Exponentiation: ^
  • 2. Unary & Multiplicative: unary -, *, /, %
  • 3. Additive & Bitwise Shift: +, -, <<, >>
  • 4. Relational & Equality: <, <=, >, >=, ==, !=
  • 5. Compound Assignment & Inc/Dec: +=, -=, *=, /=, %=, <<=, >>=, &=, |=, ++, --
  • 6. Bitwise & Logical: &, |, &&, ||, ~ (logical NOT)
  • 7. Ternary Conditional: ?:
  • 8. Statement Assignment & Separator: =, ;
Operator Semantics & Boolean Rules
Equality & Relational (==, !=, <, <=, >, >=)
Returns 1.0 when true and 0.0 when false. == and != compare values within Epsilon (1e-12).
Logical Connectives (&&, ||, ~)
x && y returns 1.0 if x > 0 and y > 0; x || y returns 1.0 if either > 0; ~x (logical NOT) returns 1.0 if not x > 0. Bitwise AND/OR use & and |.
Ternary (cond ? true-stmts : false-stmts)
Evaluates true-stmts if cond != 0, otherwise false-stmts. Only one ternary conditional is allowed per statement.
Loops & Branches (if, for, while, do)
if(cond, nonzero, zero), for(init, cond, stmts), while(cond, stmts), and do(cond, stmts) iterate while cond != 0.
Syntax & Semantics Rules
  • Case Insensitivity: Symbols and built-in identifiers are case insensitive.
  • Statements & Assignments: Statements are separated by ; and consist of variable assignments or the final return expression. Assignment starts a statement—it is not an operator—and at most one ternary conditional (x ? y : z) is permitted per statement.
  • Variable Naming: Single-character names are reserved for built-ins; assigning to one throws an exception (e.g., r=3.0; r raises Attempted assignment to non-UserSymbol 'r'). Custom variables must use two or more letters only (e.g., Xi, not X1).
  • Unary vs. Binary Precedence: Unary operators have lower precedence than exponentiation: -3^2 evaluates as -(3^2) = -9. Use parentheses ((-3)^2 = 9) to override.
  • Division & Implicit Multiplication: 1/2x is parsed as (1/2)x; write 1/(2*x) explicitly when dividing by a product.
  • Subtracting Negative Numbers: Because -- is the decrement operator, wrap negative right-hand operands in parentheses: -4-(-5).

Source Images, Pixel Addressing & Channels

Image Sequence Indexes

u and v reference the first and second images in the sequence. Index any image reference with brackets (0-based; negative indexes count from the end; out-of-range indexes wrap around, so in a 3-image list u[-1], u[2], and u[5] all select the third image):

  • u[0] First image
  • u[2] Third image
  • u[-1] Last image in list
  • u[t] Current image (s)

Average the first and third images (the second image at index 1 is ignored and discarded):

$ magick image1.jpg image2.jpg image3.jpg -fx "(u+u[2])/2" image.jpg
Pixel & Neighborhood Access

All color values are normalized to 0.0–1.0 (alpha ranges from 0.0 transparent to 1.0 opaque). By default, p, r, g, b, and a read from s (equivalent to u except inside %[fx:...]).

Relative Indexing (Brackets):
p[-1].g
Green value of pixel immediately left of current pixel
p[-1,-1].r
Red value of pixel diagonally up and left
Absolute Coordinates (Braces):
p{0,0}.r
Red value of upper-left corner pixel
p{12,34}.b
Blue value at column 12, row 34

Fractional coordinates return blended colors according to -interpolate, and out-of-bounds coordinates follow -virtual-pixel.

Channel Selection & Output Channels

Use -channel to choose which output channels -fx updates (by default, all channels except opacity are updated). Appending a channel qualifier such as u.r reads a specific input channel; omitting it reads the active channel. Use mean.this for the current channel's mean or mean.all for the overall mean across channels.

Replace the red channel of alpha.png with the average of the green channels from alpha.png and beta.png:

$ magick alpha.png beta.png -channel red -fx "(u.g+v.g)/2" gamma.png

Because only the first image (u) is cloned and modified on the selected -channel green, blending a flopped logo with an unflopped logo produces an asymmetric result:

$ magick logo: -flop logo: -resize "20%" -channel green -fx "(u+v)/2" image.jpg
logo-sm-flop.png logo-sm.png logo-sm-fx.png

Results & Format Escapes

When -fx runs, computed channel values are written into a clone of u (s = u, t = 0), which then replaces the entire input image list. Instead of modifying image pixels, FX expressions can also be evaluated inside -format and -set string escapes:

%[fx:...] Value Escape

Evaluated once per image in the sequence (s and t step through each image, i = j = 0, channel defaults to red, and -channel is ignored).

$ magick canvas:'rgb(25%,50%,75%)' rose: -colorspace gray \
  -format 'Red channel of NW corner of image #%[fx:t] is %[fx:s] ' info:
Red channel of NW corner of image #0 is 0.464883
Red channel of NW corner of image #1 is 0.184582
%[pixel:...] & %[hex:...] Color Escapes

Evaluated once per image and per color channel (-channel ignored, i = j = 0), converting the resulting channel values into a named or hexadecimal color string.

$ magick rose: -format '%[pixel:p{0,0}]' info:
Practical Escape Examples

Rotate each duplicated frame proportionally and set a longer animation pause on the first frame (t == 0):

$ magick rose: -duplicate 29 -virtual-pixel Gray -distort SRT '%[fx:360.0*t/n]' \
  -set delay '%[fx:t == 0 ? 240 : 10]' -loop 0 rose.gif

Compare two images with RMSE and return 1 if the distortion exceeds 0.1 (otherwise 0):

$ magick water.png reference.png -metric RMSE -compare -format "%[fx:%[distortion]>0.1]" info:

Convert an image modification date-time property into Unix epoch seconds using epoch():

$ magick rose.png -precision 16 -format '%[fx:epoch(%%[date:modify])]' info: