我不是ffmpeg专家,但这应该可以解决问题。
首先,您可以像这样获得输入视频的大小:
ffprobe -v error -of flat=s=_ -select_streams v:0 -show_entries stream=height,width in.mp4
使用相当新的ffmpeg,您可以使用以下选项调整视频大小:
ffmpeg -i in.mp4 -vf scale=720:480 out.mp4
您可以将宽度或高度设置为-1
,以便ffmpeg
调整视频的大小并保持宽高比。实际上,这-2
是一个更好的选择,因为计算值应该均匀。因此,您可以输入:
ffmpeg -i in.mp4 -vf scale=720:-2 out.mp4
获得视频后,720x480
由于您可以ffmpeg
计算高度,因此它可能会比预期的大,因此必须对其进行裁剪。可以这样完成:
ffmpeg -i in.mp4 -filter:v "crop=in_w:480" out.mp4
最后,您可以编写这样的脚本(可以很容易地对其进行优化,但是为了便于阅读,我将其简化了):
#!/bin/bash
FILE="/tmp/test.mp4"
TMP="/tmp/tmp.mp4"
OUT="/tmp/out.mp4"
OUT_WIDTH=720
OUT_HEIGHT=480
# Get the size of input video:
eval $(ffprobe -v error -of flat=s=_ -select_streams v:0 -show_entries stream=height,width ${FILE})
IN_WIDTH=${streams_stream_0_width}
IN_HEIGHT=${streams_stream_0_height}
# Get the difference between actual and desired size
W_DIFF=$[ ${OUT_WIDTH} - ${IN_WIDTH} ]
H_DIFF=$[ ${OUT_HEIGHT} - ${IN_HEIGHT} ]
# Let's take the shorter side, so the video will be at least as big
# as the desired size:
CROP_SIDE="n"
if [ ${W_DIFF} -lt ${H_DIFF} ] ; then
SCALE="-2:${OUT_HEIGHT}"
CROP_SIDE="w"
else
SCALE="${OUT_WIDTH}:-2"
CROP_SIDE="h"
fi
# Then perform a first resizing
ffmpeg -i ${FILE} -vf scale=${SCALE} ${TMP}
# Now get the temporary video size
eval $(ffprobe -v error -of flat=s=_ -select_streams v:0 -show_entries stream=height,width ${TMP})
IN_WIDTH=${streams_stream_0_width}
IN_HEIGHT=${streams_stream_0_height}
# Calculate how much we should crop
if [ "z${CROP_SIDE}" = "zh" ] ; then
DIFF=$[ ${IN_HEIGHT} - ${OUT_HEIGHT} ]
CROP="in_w:in_h-${DIFF}"
elif [ "z${CROP_SIDE}" = "zw" ] ; then
DIFF=$[ ${IN_WIDTH} - ${OUT_WIDTH} ]
CROP="in_w-${DIFF}:in_h"
fi
# Then crop...
ffmpeg -i ${TMP} -filter:v "crop=${CROP}" ${OUT}