main.go (2676B)
1 package main 2 3 import ( 4 "flag" 5 "fmt" 6 "image" 7 "image/png" 8 "os" 9 "strings" 10 11 _ "image/jpeg" 12 13 _ "image/png" 14 15 "git.sr.ht/~jackmordaunt/go-libwebp/v2/webp" 16 ) 17 18 func main() { 19 if err := run(os.Args[1:]); err != nil { 20 fmt.Printf("error: %v\n", err) 21 os.Exit(1) 22 } 23 } 24 25 func run(args []string) error { 26 if len(args) == 0 || isHelp(args[0]) { 27 fmt.Printf("Usage: specify command [encode, decode]\n") 28 return nil 29 } 30 if len(args) < 1 { 31 return fmt.Errorf("not enough arguments") 32 } 33 switch args[0] { 34 case "decode": 35 return decodeWebp(args[1:]) 36 case "encode": 37 return encodeWebp(args[1:]) 38 default: 39 return fmt.Errorf("unknown command: %q", args[0]) 40 } 41 } 42 43 func isHelp(s string) bool { 44 return strings.HasPrefix(s, "-h") 45 } 46 47 func encodeWebp(args []string) error { 48 var ( 49 quality float64 50 lossless bool 51 output string 52 ) 53 cli := flag.NewFlagSet("encode", flag.ExitOnError) 54 cli.BoolVar(&lossless, "lossless", false, "lossless quality, ignores quality flag") 55 cli.Float64Var(&quality, "q", 1.0, "quality from [0,1]") 56 cli.StringVar(&output, "o", "out.webp", "path to output file") 57 if err := cli.Parse(args); err != nil { 58 return err 59 } 60 if len(cli.Args()) < 1 { 61 return fmt.Errorf("provide image to encode as webp, try megopher.png") 62 } 63 input := cli.Args()[0] 64 srcf, err := os.Open(input) 65 if err != nil { 66 return fmt.Errorf("opening input file: %w", err) 67 } 68 defer srcf.Close() 69 dstf, err := os.Create(output) 70 if err != nil { 71 return fmt.Errorf("opening output file: %w", err) 72 } 73 defer dstf.Close() 74 img, _, err := image.Decode(srcf) 75 if err != nil { 76 return fmt.Errorf("decoding src image: %w", err) 77 } 78 opts := []webp.EncodeOption{} 79 opts = append(opts, webp.Quality(float32(quality))) 80 if lossless { 81 opts = append(opts, webp.Lossless()) 82 } 83 if err := webp.Encode(dstf, img, opts...); err != nil { 84 return fmt.Errorf("encoding webp: %w", err) 85 } 86 return nil 87 } 88 89 func decodeWebp(args []string) error { 90 var output string 91 cli := flag.NewFlagSet("decode", flag.ExitOnError) 92 cli.StringVar(&output, "o", "out.png", "path to output file") 93 if err := cli.Parse(args); err != nil { 94 return err 95 } 96 if len(cli.Args()) < 1 { 97 return fmt.Errorf("provide image to encode as webp") 98 } 99 input := cli.Args()[0] 100 srcf, err := os.Open(input) 101 if err != nil { 102 return fmt.Errorf("opening input file: %w", err) 103 } 104 defer srcf.Close() 105 dstf, err := os.Create(output) 106 if err != nil { 107 return fmt.Errorf("opening output file: %w", err) 108 } 109 defer dstf.Close() 110 img, err := webp.Decode(srcf) 111 if err != nil { 112 return fmt.Errorf("decoding src image: %w", err) 113 } 114 if err := png.Encode(dstf, img); err != nil { 115 return fmt.Errorf("encoding webp: %w", err) 116 } 117 return nil 118 }