Skip to content

Instantly share code, notes, and snippets.

@Shchvova
Last active February 24, 2023 18:50
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 Shchvova/4e8c24f35340166c515f7e8ae48b526f to your computer and use it in GitHub Desktop.
Save Shchvova/4e8c24f35340166c515f7e8ae48b526f to your computer and use it in GitHub Desktop.
Screen recording to gif advanced
#!/bin/zsh
function help {
echo "Easily make gifs from screen recordings
> to install on macOS:
brew install imagemagick ffmpeg
sudo curl https://gist.githubusercontent.com/shchvova/4e8c24f35340166c515f7e8ae48b526f/raw/togif > /usrl/local/bin/togif
sudo chmod +x /usrl/local/bin/togif
> usage
togif ~/Desktop/ScreenRecording.mov
or
PTS=0.75 FPS=15 togif ~/Desktop/ScreenRecording.mov
to customize speed and FPS of output. Displayed values are default
"
}
set -e
INPUT="$1"
if [ ! -f "$INPUT" ]
then
help
exit 1
fi
EXT="${INPUT##*.}"
OUT="${INPUT%.*}.gif"
DIR="$(mktemp -d)"
MASK_FILE="${INPUT%.*}_mask_crop.png"
PALETTE_FILE="$DIR/palette.png"
CROPPED_VID="$DIR/cropped.$EXT"
trap 'rm -f -- "$MASK_FILE" "$PALETTE_FILE" "$CROPPED_VID"; rmdir "$DIR"' EXIT SIGINT
ffmpeg -loglevel error -hide_banner -y -ss 0:00:00.1 -i "$INPUT" -vf "drawtext=text='Create mask for your GIF
Select and DELET area you want to become GIF
then save ⌘S, close and switch back to terminal': fontsize=trunc(w/50): fontcolor=white:box=1:boxcolor=black@0.7: x=(w-text_w)/2:y=(h-text_h)/2" -frames:v 1 "$MASK_FILE"
open -a Preview "$MASK_FILE"
echo
echo "Now create a mask for your gif to specify which part of the recording should be giffed. Select and DELETE part of image you want to be a gif, save ⌘S it, close Preview. Then press Enter to continue"
read -k1 -s
echo "Thanks. Generating your gif..."
IFS=$'\n' COORDS=($(convert "$MASK_FILE" -alpha extract TXT:- | grep -Fv '#FFFFFF' | sed -n '2p;$p' | cut -d':' -f1))
rm -f -- "$MASK_FILE"
CROP=""
if [ -n "${COORDS[2]}" ] && [ -z "${COORDS[3]}" ]
then
START=(${(@s:,:)${COORDS[1]}})
END=(${(@s:,:)${COORDS[2]}})
(( WIDTH = $END[1] - $START[1] ))
(( HEIGHT = $END[2] - $START[2] ))
CROP="crop=$WIDTH:$HEIGHT:${START[1]}:${START[2]},"
fi
ffmpeg -loglevel error -hide_banner -y -i "$INPUT" -filter:v "$CROP setpts=${PTS:-0.75}*PTS, fps=${FPS:-15} $FILTERS" "$CROPPED_VID"
ffmpeg -loglevel error -hide_banner -y -i "$CROPPED_VID" -filter_complex "[0:v] palettegen" "$PALETTE_FILE"
ffmpeg -loglevel error -hide_banner -y -i "$CROPPED_VID" -i "$PALETTE_FILE" -filter_complex "[0:v][1:v] paletteuse" "$OUT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment