This is my code that adds an image to videos, running via PHP:
exec('ffmpeg -i input.mp4 -i logo.png -filter_complex "[0:v][1:v] overlay=10:10" -pix_fmt yuv420p -c:a copy output.mp4');
It works well but the problem is, the image is scaled down or up, up on the video resolution. For example in the following images the logo width is 50px
but videos resolution are different:
and this one
How can I prevent the image from scaling down/up ?
Thanks to Mulvya, he proposed these codes
ffmpeg -i input.mp4 -i logo.png -filter_complex "[1:v][0:v]scale2ref=(W/H)*ih/8:ih/8[wm][base];[base][wm]overlay=10:10" -pix_fmt yuv420p -c:a copy output.mp4
and
ffmpeg -i input.mp4 -i logo.png -filter_complex "[1:v][0:v]scale2ref=(W/H)*ih/8:ih/8[wm][base];[wm]setsar=1[wmsar]; [base][wmsar]overlay=10:10" -pix_fmt yuv420p -c:a copy output.mp4
that works very well, but it doesn't keep the logo aspect ratio. I tried this code on two videos with different resolution and this is the result
and this one
Is it possible to improve this solution?
FFmpeg offers the overlay filter as a way to overlay images (or even other videos) onto video streams. To centre overlay/watermark on a video, use this command: ffmpeg -i inputvideo.avi -i watermarklogo.png -filter_complex \ "overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2" -codec:a copy output.flv.
You can use the scale2ref filter.
ffmpeg -i input.mp4 -i logo.png -filter_complex "[1:v][0:v]scale2ref=(W/H)*ih/8/sar:ih/8[wm][base];[base][wm]overlay=10:10" -pix_fmt yuv420p -c:a copy output.mp4
This will resize the logo's height to 1/8th of the height of the video.
You have to replace W/H
with the values for the image e.g. if the PNG is 320x270, then it should be scale2ref=(320/270)*ih/8:ih/8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With