How to Overlay Images Using ImageMagick?
Overlaying one image on top of another is a common task in image
processing, easily achieved using ImageMagick’s composite
operator within the convert (or magick)
command. This article provides a quick overview of how to blend a
foreground image onto a background image, control the positioning using
gravity and offsets, and adjust transparency levels for seamless
compositing.
The Basic Overlay Command
The fundamental syntax for layering a foreground image onto a background image requires specifying the background first, the foreground second, the composition method, and the final output filename.
magick convert background.jpg foreground.png -composite output.jpgNote: If you are using ImageMagick v7 or newer, the
converttool is built into the primarymagickcommand, so you can simply start the command withmagick background.jpg ...instead ofmagick convert.
Positioning the Overlay
By default, ImageMagick places the foreground image in the top-left
corner (NorthWest) of the background image. You can precisely control
this placement using the -gravity and
-geometry flags.
Using Gravity for General Alignment
The -gravity option allows you to anchor the foreground
image to specific regions of the background, such as the center or the
corners.
- Center:
-gravity Center - Bottom Right:
-gravity SouthEast - Top Center:
-gravity North
magick convert background.jpg foreground.png -gravity Center -composite output.jpgUsing Geometry for Precise Offsets
If you need to nudge the image away from its gravity anchor, append a
-geometry offset specified in pixels
(+X+Y).
magick convert background.jpg foreground.png -gravity SouthEast -geometry +20+10 -composite output.jpgIn this example, the foreground image is anchored to the bottom-right corner but shifted 20 pixels to the left and 10 pixels up.
Adjusting Transparency and Blend Modes
If your foreground image does not already have an alpha channel (transparency), or if you want to make the entire overlay semi-transparent, you can dissolve the images together.
Setting Global Transparency
The -define compose:args option combined with the
Dissolve operator allows you to set a percentage for the
foreground’s opacity.
magick convert background.jpg foreground.png -define compose:args=50 -compose Dissolve -composite output.jpgThis blends the foreground at 50% opacity onto the background image.