How To Trim APNG Images Using FFMPG?

Ivan Terekhin
1 min readMay 18, 2023

--

Recently I’ve faced this task in my work, so, tried to automate it a bit.

Mostly Generated by ChatGPT

To trim transparent pixels from an APNG (Animated PNG) image using FFmpeg, you can follow these steps:

1. First, make sure you have FFmpeg installed on your system. If not, you can download it from the official website: https://ffmpeg.org/download.html.

2. Convert the APNG to individual PNG frames. Create a folder named `frames` to store the extracted frames:

mkdir frames
ffmpeg -i input.apng -vsync 0 frames/frame_%03d.png

3. Install ImageMagick to crop the transparent pixels. You can download it from the official website: https://imagemagick.org/script/download.php.

4. Use ImageMagick to find the bounding box for all the frames:

convert frames/frame_*.png -define registry:temporary-path=./tmp -trim -layers merge +repage -format “%@” info: > bbox.txt

This command will create a `bbox.txt` file containing the common bounding box for all the frames.

5. Read the `bbox.txt` file and store the bounding box values in a variable:

bbox=$(cat bbox.txt)

6. Use ImageMagick to crop all the frames using the common bounding box:

mogrify -crop $bbox +repage frames/frame_*.png

7. Convert the cropped frames back into an APNG file:

ffmpeg -framerate F -i frames/frame_%03d.png -c:v apng -plays 0 output.apng

Replace `F` with the original frame rate of the input APNG.

--

--

Ivan Terekhin
Ivan Terekhin

Written by Ivan Terekhin

Mobile developer (Android, iOS, Flutter), AI and GameDev enthusiast. https://www.indiehackers.com/jeuler

No responses yet