To merge two images into a single composite image using FFmpeg, you must use the
overlay video filter within a video processing pipeline. Although FFmpeg is primarily a video tool, it can treat static images as single-frame videos to perform spatial composition, placing one image on top of another at specified coordinates. This method allows for precise control over positioning, scaling, and transparency without requiring external graphic design software or complex scripting languages.
Understanding the FFmpeg Image Processing Workflow
FFmpeg does not have a native "merge images" command that outputs a static file like PNG or JPEG directly from two inputs in a single simple step. Instead, it treats each image input as a video stream with a duration of one second (or less). To combine them, you create a virtual video timeline where both images exist simultaneously. The
overlay filter is the core mechanism that takes the second video stream (the overlay) and draws it onto the first video stream (the background).
This approach is particularly useful when you need to automate visual tasks via the command line, such as adding watermarks, creating picture-in-picture effects, or composing collages programmatically. For more advanced animations involving multiple images, you might explore how to
Combine Images and Draw Text on Each Image with Animation Xfade, which utilizes similar filtering concepts but adds temporal transitions.
Basic Command for Side-by-Side Merging
The most common use case is placing two images side by side or stacking them vertically. Below is the standard command structure for merging two images,
bg.png and
fg.png, into a new output file.
ffmpeg -i bg.png -i fg.png -filter_complex "overlay=x:y" -frames:v 1 output.png
Let's break down the critical components of this command:
- -i bg.png: Specifies the background image. This is the base layer.
- -i fg.png: Specifies the foreground image. This is the layer that will be overlaid.
- -filter_complex: Indicates that we are using a complex filter graph. This is necessary because we are combining multiple inputs.
- "overlay=x:y": This is the filter instruction.
x and y represent the horizontal and vertical coordinates where the top-left corner of the foreground image should be placed relative to the background. Replace x and y with actual pixel values (e.g., overlay=100:50). If you omit these, FFmpeg defaults to placing the overlay at position 0,0 (top-left), which often results in the foreground covering the entire background if sizes match.
- -frames:v 1: This is crucial. It tells FFmpeg to encode only one frame of video. Since we are merging static images, we do not want a one-second video file; we want a single still image.
- output.png: The final output file. You can change this to
.jpg or .bmp depending on your needs.
Handling Different Image Sizes and Scaling
If your two images have different dimensions, simply using
overlay may result in unexpected behavior or errors if the coordinate system does not align. For example, if the background is 1920x1080 and the foreground is 300x300, you can place the foreground anywhere within those bounds. However, if you try to overlay a larger image onto a smaller one, FFmpeg may crop or scale unexpectedly.
To ensure compatibility, you should scale the foreground image to fit within the background's dimensions before overlaying it. You can achieve this by expanding the filter complex.
ffmpeg -i bg.png -i fg.png -filter_complex "[1:v]scale=300:300[ovr];[0:v][ovr]overlay=10:10" -frames:v 1 output.png
In this example:
- [1:v]: Refers to the video stream of the second input (
fg.png).
- scale=300:300: Resizes the foreground image to 300 pixels wide and high. Label this output stream as
[ovr].
- [0:v]: Refers to the video stream of the first input (
bg.png).
- [0:v][ovr]overlay=10:10: Overlays the scaled
[ovr] stream onto the [0:v] stream at coordinates 10,10.
This technique ensures that regardless of the original size of
fg.png, it will be resized correctly before being composited. Always verify that the scaled dimensions do not exceed the background resolution to avoid clipping issues.
Adding Transparency and Alpha Channels
One of the greatest advantages of using FFmpeg for image merging is its support for alpha channels. If your foreground image has transparent areas (such as a PNG with a transparent background), the
overlay filter will respect that transparency by default. The underlying parts of the background image will show through the transparent sections of the foreground.
However, if you are working with JPEG files, which do not support transparency, you cannot create true alpha blending. In such cases, the overlay will completely obscure the background pixels beneath it. For professional compositing, always prefer PNG or TIFF formats for intermediate steps to preserve quality and transparency data.
For users who need to integrate these merged images into broader media projects, understanding how to handle image sequences is vital. You can learn more about converting existing video content into image sequences in our guide on
FFmpeg: Video to Images - Convert Video to Images with FFmpeg, which complements this workflow by allowing you to extract frames, modify them, and reassemble them.
Troubleshooting Common Issues
Even with straightforward commands, several common pitfalls can arise during the merging process. Understanding these helps streamline your workflow and saves debugging time.
The Output is Black or Blank
A frequent issue is receiving a black output file instead of the merged image. This usually happens because the coordinate values for
overlay are set outside the visible area of the background image. For instance, if the background is 800x600 and you set
overlay=1000:1000, the foreground is drawn off-screen. Ensure your
x and
y values are less than the width and height of the background image, respectively. Additionally, check that the input files are not corrupted and that FFmpeg successfully reads them by testing with
ffprobe input.png.
Color Distortion or Incorrect Colors
If the colors in the output image look washed out or incorrect, it may be due to color space conversion. FFmpeg handles various color spaces (like YUV vs RGB). When merging images, especially those with specific color profiles, ensure that both inputs share the same color space or let FFmpeg handle the conversion automatically. Adding
-pix_fmt rgba to the output command can sometimes force the correct pixel format for PNGs with transparency.
Performance Lag with Large Images
Processing high-resolution images (4K or higher) can be resource-intensive. If you experience lag, consider downsampling the images before processing or using hardware acceleration flags like
-hwaccel if your GPU supports it. However, for simple overlays, CPU processing is usually sufficient unless dealing with massive batch operations.
Frequently Asked Questions
Can I merge more than two images at once?
Yes, you can merge multiple images by extending the filter complex. Add additional
-i arguments for each image and chain them together in the
filter_complex string using multiple
overlay filters. Each subsequent overlay is applied to the result of the previous one, allowing for complex multi-layer compositions.
Does FFmpeg support animated GIFs as inputs?
Yes, FFmpeg can read animated GIFs as input streams. However, treating an animated GIF as a single frame requires careful handling. By default, FFmpeg reads the first frame. To merge a specific frame from an animated GIF, you may need to use the
-ss flag to seek to a specific timestamp or use the
vframe option to limit the output frames, ensuring only the desired static frame is used in the overlay.
How do I center an image perfectly on the background?
To center an image, you must calculate the coordinates mathematically. Subtract the width of the foreground image from the width of the background image, then divide by two for the X coordinate. Do the same for the height to get the Y coordinate. For example, if the background is 1920x1080 and the foreground is 400x400, the center X is (1920-400)/2 = 760, and Y is (1080-400)/2 = 340. Use
overlay=760:340 in your command.
Why is my output file much larger than expected?
Image compression settings significantly impact file size. If you output a PNG, FFmpeg uses default compression levels which may not be optimal. You can reduce file size by adjusting the compression level using
-compression_level (for PNG) or by converting to JPEG with a lower quality setting using
-q:v. Always compare the source and destination file sizes to ensure efficient storage usage.
Can I use this method to add a watermark to a video?
Absolutely. This exact workflow is commonly used for watermarking. Instead of providing two images as inputs, you provide one video and one image (the logo). The
overlay filter places the logo image over the video stream throughout its duration. You can also animate the watermark's position by using variables like
t (time) in the
overlay coordinates to move the logo across the screen.