go-libwebp

Experimental translation from libwebp to Go source.
Log | Files | Refs | README | LICENSE

commit 8000e873f42d591bd04c69a3479ee4f467eda880
parent b2fb224c1f9613d70f27c7ac28a185acabc7901c
Author: Jack Mordaunt <jackmordaunt.dev@gmail.com>
Date:   Sat, 29 Jan 2022 19:30:45 +0800

webp/cmd: showcase decoding

Nothing special, since it just defers to x/image/webp.

Signed-off-by: Jack Mordaunt <jackmordaunt.dev@gmail.com>

Diffstat:
Mcmd/main.go | 65+++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
1 file changed, 57 insertions(+), 8 deletions(-)

diff --git a/cmd/main.go b/cmd/main.go @@ -5,35 +5,51 @@ import ( "fmt" "image" "os" - "runtime" _ "image/jpeg" + "image/png" _ "image/png" "git.sr.ht/~jackmordaunt/go-libwebp/webp" ) func main() { - runtime.LockOSThread() if err := run(os.Args[1:]); err != nil { fmt.Printf("error: %v\n", err) } } func run(args []string) error { + if len(args) < 1 { + return fmt.Errorf("not enough arguments") + } + switch args[0] { + case "decode": + return decodeWebp(args[1:]) + case "encode": + return encodeWebp(args[1:]) + default: + return fmt.Errorf("unknown command: %q", args[0]) + } +} + +func encodeWebp(args []string) error { var ( quality float64 lossless bool output string ) - flag.BoolVar(&lossless, "lossless", false, "lossless quality, ignores quality flag") - flag.Float64Var(&quality, "q", 1.0, "quality from [0,1]") - flag.StringVar(&output, "o", "out.webp", "path to output file") - flag.Parse() - if len(flag.Args()) < 1 { + cli := flag.NewFlagSet("encode", flag.ExitOnError) + cli.BoolVar(&lossless, "lossless", false, "lossless quality, ignores quality flag") + cli.Float64Var(&quality, "q", 1.0, "quality from [0,1]") + cli.StringVar(&output, "o", "out.webp", "path to output file") + if err := cli.Parse(args); err != nil { + return err + } + if len(cli.Args()) < 1 { return fmt.Errorf("provide image to encode as webp, try megopher.png") } - input := flag.Args()[0] + input := cli.Args()[0] srcf, err := os.Open(input) if err != nil { return fmt.Errorf("opening input file: %w", err) @@ -53,3 +69,36 @@ func run(args []string) error { } return nil } + +func decodeWebp(args []string) error { + var ( + output string + ) + cli := flag.NewFlagSet("decode", flag.ExitOnError) + cli.StringVar(&output, "o", "out.png", "path to output file") + if err := cli.Parse(args); err != nil { + return err + } + if len(cli.Args()) < 1 { + return fmt.Errorf("provide image to encode as webp") + } + input := cli.Args()[0] + srcf, err := os.Open(input) + if err != nil { + return fmt.Errorf("opening input file: %w", err) + } + defer srcf.Close() + dstf, err := os.Create(output) + if err != nil { + return fmt.Errorf("opening output file: %w", err) + } + defer dstf.Close() + img, err := webp.Decode(srcf) + if err != nil { + return fmt.Errorf("decoding src image: %w", err) + } + if err := png.Encode(dstf, img); err != nil { + return fmt.Errorf("encoding webp: %w", err) + } + return nil +}