How to Convert APNG to MP4 with FFmpeg
Converting an Animated Portable Network Graphics (APNG) file into a standard MP4 video is a straightforward process using the open-source multimedia framework FFmpeg. This guide provides the exact commands needed to encode APNG animations into universally compatible H.264 MP4 files, detailing crucial options for pixel format conversion, dimension fixes, and transparency handling to ensure smooth playback across all media players and web browsers.
The Standard Conversion Command
To convert an APNG file to a standard, universally compatible MP4 video, open your terminal or command prompt and run:
ffmpeg -i input.apng -c:v libx264 -pix_fmt yuv420p output.mp4Parameter Breakdown
-i input.apng: Specifies the input APNG file path.-c:v libx264: Selects the H.264 video codec, which provides high compression efficiency and universal compatibility with web browsers, operating systems, and media players.-pix_fmt yuv420p: Sets the pixel format to YUV 4:2:0 planar. APNG files typically use RGB or RGBA color spaces, which are not supported by most standard MP4 decoders (such as Apple QuickTime or older mobile devices). This flag is mandatory for wide compatibility.output.mp4: Specifies the destination file name.
Handling Odd Dimensions
The H.264 encoder requires the video's width and height to be even numbers (divisible by 2). If your APNG file has odd dimensions (e.g., 501x300), the conversion will fail with an error.
To automatically pad the dimensions to the nearest even number without distorting the image, add a video filter:
ffmpeg -i input.apng -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" -c:v libx264 -pix_fmt yuv420p output.mp4Handling Transparency
Standard MP4 files do not support alpha (transparency) channels. By default, any transparent areas in your APNG will render as black pixels.
If you want to place the animation over a custom background color
(such as white) instead of black, use the colorchannelmixer
and overlay filters:
ffmpeg -f lavfi -i color=white:s=WIDTHxHEIGHT -i input.apng -filter_complex "[0:v][1:v]overlay=shortest=1" -c:v libx264 -pix_fmt yuv420p output.mp4Replace WIDTHxHEIGHT with the exact dimensions of your
APNG file (e.g., 800x600), or replace white
with any desired hex color code (e.g., 0xFFFFFF).
Controlling Quality and Framerate
You can adjust visual quality and file size using the Constant Rate
Factor (-crf) parameter, where lower values mean higher
quality (sensible values range from 18 to 28):
ffmpeg -i input.apng -c:v libx264 -crf 20 -pix_fmt yuv420p output.mp4If you need to enforce a specific output framerate, use the
-r flag:
ffmpeg -r 30 -i input.apng -c:v libx264 -pix_fmt yuv420p output.mp4