How to Trim Image Whitespace with ImageMagick?

Removing unnecessary blank borders from an image is a common task in graphics processing that can be easily automated using ImageMagick. This article provides a quick guide on how to use the convert command (or the magick command in newer versions) alongside the -trim operator to automatically crop away uniform background whitespace. You will learn the basic command syntax, how to use fuzz factor to remove near-white borders, and how to add padding back to the trimmed image for a cleaner look.


The Basic Trim Command

The most straightforward way to remove a solid white or transparent border from an image is by using the -trim operator. ImageMagick looks at the pixels in the corners of the image, determines the background color, and crops away any matching color on the outer edges.

convert input.png -trim output.png

Note: If you are using ImageMagick v7 or later, the convert command has been replaced by the primary magick command, though convert is often still supported as a legacy alias: magick input.png -trim output.png

Handling Off-White Borders with Fuzz

Sometimes, an image border looks white but contains slight variations, compression artifacts, or shadows. If the background isn’t 100% uniform, the standard -trim command might fail to remove it. To fix this, you can introduce the -fuzz option, which allows ImageMagick to treat colors that are nearly identical to the background as a match.

convert input.png -fuzz 5% -trim output.png

The 5% value tells the tool to accept a 5% color variance. You can increase this percentage (e.g., 10% or 15%) if the background is particularly noisy, but be careful not to set it too high, or you might accidentally crop out parts of the actual subject.

Retaining Canvas Info vs. Resetting Page

When you trim a GIF or a PNG, ImageMagick sometimes keeps the original canvas dimensions embedded in the file metadata as a virtual canvas. This can cause issues when you try to display the image in certain web browsers or image viewers. To completely reset the canvas size to match the newly cropped dimensions, append the +repage operator after trimming.

convert input.png -fuzz 5% -trim +repage output.png

Adding a Clean Padding After Trimming

Trimming an image perfectly to its edges can sometimes look too cramped. If you want to remove the irregular, messy whitespace but still keep a clean, uniform border around your subject, you can combine -trim with the -border option.

convert input.png -trim -bordercolor white -border 10x10 +repage output.png

In this command: