Skip to content

Instantly share code, notes, and snippets.

@fabioam
Created November 4, 2017 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabioam/c7a4343352b73f48a9b48c5b993e7180 to your computer and use it in GitHub Desktop.
Save fabioam/c7a4343352b73f48a9b48c5b993e7180 to your computer and use it in GitHub Desktop.
Convert mp4 video to instagram portrait format (720wx1080h)
#!/bin/bash
# 99% of credits by https://unix.stackexchange.com/a/192021/235601
if [ "$#" -ne 1 ]
then
echo "Description: Convert mp4 file to instagram portrait format (720wx1080h)"
echo "Usage: $0 <filename>"
exit 1
fi
FILE=$1
TMP="tmp.mp4"
OUT="$1-instagram.mp4"
OUT_WIDTH=720
OUT_HEIGHT=1080
# 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}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment