Last active
January 18, 2026 10:10
-
-
Save Mrfiregem/f00c896537eaf1639325329cf5aa9f13 to your computer and use it in GitHub Desktop.
Create a gif from a section of a video file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env nu | |
| const dither_styles = [bayer, hackbert, floyd_steinberg, sierra2, sierra2_4a, sierra3, burkes, atkinson, none] | |
| # Create a gif from a given video file | |
| def main [ | |
| video: path # Path to the source video | |
| output: path # Path to save gif to | |
| start_time: number = 0 # When in the video the gif should start | |
| duration: number = 30 # How Long the gif should be in seconds | |
| --fps(-f): int = 15 # Fps of the resulting gif | |
| --width(-w): int = 320 # Width of the gif (height scales) | |
| --max-colors(-c): int = 32 # Number of colors allowed for the palette (max 255) | |
| --dither-style(-d): string@$dither_styles = 'bayer' # Dithering method for gif output | |
| ]: nothing -> nothing { | |
| # Remove all non-alphanumeric or '_' characters to prevent malicious input | |
| let dither_style = $dither_style | str replace -ar '[^a-zA-Z0-9_]' '' | str downcase | |
| if $dither_style not-in $dither_styles { | |
| print -e $'Invalid dither style: "($dither_style)"' | |
| print -e 'Possible values:' | |
| $dither_styles | grid -s ' ' -w 40 | print -e | |
| exit 1 | |
| } | |
| # Create a tempfile to save palette to | |
| let palette = mktemp -t --suffix '.png' | |
| # Generate gif filterline | |
| let filters = $'fps=($fps),scale=($width):-1:flags=lanczos' | |
| # Generate palette file | |
| ^ffmpeg -v warning -ss $start_time -t $duration -i $video -vf $'($filters),palettegen=max_colors=($max_colors)' -frames:v 1 -update 1 -y $palette | |
| # Generate gif output | |
| ^ffmpeg -v warning -ss $start_time -t $duration -i $video -i $palette -lavfi $'($filters) [x]; [x][1:v] paletteuse=dither=($dither_style)' -y $output | |
| # Cleanup | |
| rm $palette | |
| print $'Output: ($output | path expand)' | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment