Skip to content

Instantly share code, notes, and snippets.

@zahlman
Created April 16, 2026 23:20
Show Gist options
  • Select an option

  • Save zahlman/a682da742f49452e8769f489f200fb3a to your computer and use it in GitHub Desktop.

Select an option

Save zahlman/a682da742f49452e8769f489f200fb3a to your computer and use it in GitHub Desktop.
Crop a specified video file to the given x/y/width/height, with the same codec (will still necessarily re-encode).
#!/bin/bash
roundmul() {
lhs=$1
denom=1
case $lhs in
*px)
printf %.0f "${lhs%px}"
return
;;
*%)
lhs="${lhs%\%}"
denom=100
;;
esac
printf %.0f $(echo "scale=6; ($lhs) * ($2) / $denom" | bc)
}
rawprobe() {
ffprobe -v -8 -show_entries "stream=$1" -of 'csv=p=0:s=\ ' "$2"
}
wh=($(rawprobe width,height "$1"))
w=${wh[0]}
h=${wh[1]}
codec=$(rawprobe codec_name "$1")
crop="$(roundmul $4 $w):$(roundmul $5 $h):$(roundmul $2 $w):$(roundmul $3 $h)"
outfile="${1%.*}.cropped.${1##*.}"
ffmpeg -i "$1" -c $codec -vf "crop=$crop" "$outfile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment