Created
November 6, 2019 14:28
-
-
Save trdarr/3aec754a914aa661db1161eae15c2af8 to your computer and use it in GitHub Desktop.
convert a video to a gif, maybe
This file contains 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
package main | |
import ( | |
"fmt" | |
"os" | |
"os/exec" | |
"path/filepath" | |
"strings" | |
) | |
func main() { | |
in, err := inPath() | |
if err != nil { | |
panic(err) | |
} | |
out, err := outPath(in) | |
if err != nil { | |
panic(err) | |
} | |
if err := convert(in, out); err != nil { | |
panic(err) | |
} | |
} | |
func inPath() (string, error) { | |
if len(os.Args) < 2 { | |
return "", fmt.Errorf("no input") | |
} | |
var in string | |
in, err := filepath.Abs(os.Args[1]) | |
if err != nil { | |
return "", err | |
} | |
if _, err := os.Stat(in); os.IsNotExist(err) { | |
return "", fmt.Errorf("no such file: %s", in) | |
} | |
return in, nil | |
} | |
func outPath(in string) (string, error) { | |
if len(os.Args) > 2 { | |
out, err := filepath.Abs(os.Args[2]) | |
if err != nil { | |
return "", err | |
} | |
return out, nil | |
} | |
out, err := filepath.Abs(strings.TrimSuffix(in, filepath.Ext(in)) + ".gif") | |
if err != nil { | |
return "", err | |
} | |
return out, nil | |
} | |
func convert(in, out string) error { | |
if err := generatePalette(in); err != nil { | |
return err | |
} | |
if err := convertToGif(in, out); err != nil { | |
return err | |
} | |
return nil | |
} | |
func generatePalette(in string) error { | |
args := []string{ | |
"-y", | |
"-i", | |
in, | |
"-vf", | |
"fps=15,scale=320:-1:flags=lanczos,palettegen", | |
filepath.Join(os.TempDir(), "palette.gif"), | |
} | |
return run("ffmpeg", args...) | |
} | |
func convertToGif(in, out string) error { | |
args := []string{ | |
"-y", | |
"-i", | |
in, | |
"-i", | |
filepath.Join(os.TempDir(), "palette.gif"), | |
"-filter_complex", | |
"fps=15,scale=400:-1:flags=lanczos[x];[x][1:v]paletteuse", | |
out, | |
} | |
return run("ffmpeg", args...) | |
} | |
func run(command string, args ...string) error { | |
cmd := exec.Command(command, args...) | |
if output, err := cmd.CombinedOutput(); err != nil { | |
fmt.Println(string(output)) | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment