Transparent Watermarks with GD and Ffmpeg

I've just needed to create a text overlay on a video using a transparent PNG file. This could be a watermark or similar but I'm using it for a different purpose. Here's some php code to create an image suitable for using as an overlay in ffmpeg.

$image = imagecreatetruecolor(500, 250);
$bg = imagecolorallocatealpha($image, 255, 255, 255, 127); // Background fill colour
$fg = imagecolorallocate($image, 255, 0, 0);

imagefill($image, 0, 0, $bg); // Flood the background with the transparent colour
$text = 'Some text';

$tempfile = "a_temp_file.png";

imagettftext($image, 20, 0, 5, 30, $fg, "your_font_file", $text); // Note - doesn't need the .ttf extension
imagesavealpha($image, true); // Make sure the alpha channel is saved
imagepng($image, $tempfile); // Save to wherever you need to
imagedestroy($image); // Free up the memory

Here's a snippet to overlay an image onto a video in the centre with cropping to the aspect ratio of the original and keeping it 10px from the video bounds.

ffmpeg -i input_video.mp4 -vf "movie='overlay.png', crop=iw-20:ih-20:0:0:dar [img]; [in] [img] overlay=(W-w)/2:(H-h)/2 [out]" -vcodec mpeg4 -f mp4 out.mp4

There are plenty of posts that deal with the ffmpeg part all over the web but just as a quick description of what it does.

-i is the input file

-vf "movie='overlay.png', crop=iw-20:ih-20:0:0:dar [img];"

Use the overlay.png as a movie file. Crop it to the input (input_video.mp4 video) height and with minus 20px and keep aspect ratio with the 'dar' option. Save the result as the variable [img] in the next part of the filter chain.

[in] [img] overlay=(W-w)/2:(H-h)/2 [out]

Takes the input video file and the [img] clip created in the first part of the filter and overlays one on top of the other. Then send the result to the output stream for and carry on with the rest of your command.

Note - you need a version of ffmpeg that uses -vf and not the old style -vhook method.

This is as much a note for me as it is anyone else I guess. No point forgetting it and having to figure it out again.