How to Merge 2 Images into 1 using FFmpeg

Abstract: Merge two images into one composite file using FFmpeg overlay filter with precise positioning and scaling.

Created: 2026-07-28 by
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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More