Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ffmpeg resize down larger video to fit desired size and add padding

Tags:

padding

ffmpeg

I'm trying to resize a larger video to fit an area that I have. In order to achieve this I calculate first the dimensions of the resized video so That it fits my area, and then I try to add padding to this video so that the final result will have the desired dimension, keeping the aspect ratio as well.

So let's say that I have the original video dimensions of 1280x720 and to fit my area of 405x320 I need first to resize the video to 405x227. I do that. Everything is fine at this point. I do some math and I find out that I have to add 46 pixels of padding at the top and the bottom.

So the padding parameter of the command for that would be -vf "pad=405:320:0:46:black". But each time I run the command I get an error like Input area 0:46:405:273 not within the padded area 0:0:404:226.

The only docs for padding that I found is this http://ffmpeg.org/libavfilter.html#pad.

I don't know what I'm doing wrong. Anyone had this problem before? Do you have any suggestions?

like image 900
misterjinx Avatar asked Nov 15 '11 08:11

misterjinx


People also ask

How do I resize a video while keeping the quality high with FFmpeg?

In FFmpeg, if you want to scale a video while retaining its aspect ratio, you need to set either one of the height or width parameter and set the other parameter to -1 . That is if you set the height , then set the width to -1 and vice-versa.


2 Answers

try -vf "scale=iw*min(405/iw\,320/ih):ih*min(405/iw\,320/ih),pad=405:320:(405-iw)/2:(320-ih)/2"

Edit to clarify what's going on in that line: you are asking how to scale one box to fit inside another box. The boxes might have different aspect ratios. If they do, you want to fill one dimension, and center along the other dimension.

# you defined the max width and max height in your original question
max_width     = 405
max_height    = 320

# first, scale the image to fit along one dimension
scale         = min(max_width/input_width, max_height/input_height)
scaled_width  = input_width  * scale
scaled_height = input_height * scale

# then, position the image on the padded background
padding_ofs_x = (max_width  - input_width) / 2
padding_ofs_y = (max_height - input_height) / 2
like image 98
dooche Avatar answered Oct 31 '22 09:10

dooche


Here is a generic filter expression for scaling (maintaining aspect ratio) and padding any source size to any target size:

-vf "scale=min(iw*TARGET_HEIGHT/ih\,TARGET_WIDTH):min(TARGET_HEIGHT\,ih*TARGET_WIDTH/iw),
     pad=TARGET_WIDTH:TARGET_HEIGHT:(TARGET_WIDTH-iw)/2:(TARGET_HEIGHT-ih)/2"

Replace TARGET_WIDTH and TARGET_HEIGHT with your desired values. I use this to pull a 200x120 padded thumbnail from any video. Props to davin for his nice overview of the math.

like image 38
Seth Avatar answered Oct 31 '22 11:10

Seth