From b9515823d3579daa1496f3f5379d32f973dc17b8 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Sat, 9 May 2020 22:50:29 +0200 Subject: [PATCH] Added tool to change alpha layer of image. --- cmd/imadapt/imadapt.go | 73 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 cmd/imadapt/imadapt.go diff --git a/cmd/imadapt/imadapt.go b/cmd/imadapt/imadapt.go new file mode 100644 index 0000000..e3ae6fc --- /dev/null +++ b/cmd/imadapt/imadapt.go @@ -0,0 +1,73 @@ +package main + +import ( + "errors" + "flag" + "fmt" + "image" + "image/color" + "image/png" + "log" + "os" +) + +func run() error { + flag.Parse() + args := flag.Args() + if len(args) < 1 { + return errors.New("no command specified") + } + switch args[0] { + case "setalpha": + flags := flag.NewFlagSet("setalpha", flag.ContinueOnError) + var alpha int + flags.IntVar(&alpha, "alpha", 127, "sets the target alpha") + flags.Parse(args[1:]) + for _, path := range flags.Args() { + err := setAlpha(path, alpha) + if err != nil { + return fmt.Errorf("couldn't set alpha for '%s'; error: %v", path, err) + } + } + } + return nil +} + +func setAlpha(path string, alpha int) error { + src, err := os.Open(path) + if err != nil { + return err + } + defer src.Close() + im, _, err := image.Decode(src) + if err != nil { + return err + } + bounds := im.Bounds() + dst := image.NewNRGBA(bounds) + for y := bounds.Min.Y; y < bounds.Max.Y; y++ { + for x := bounds.Min.X; x < bounds.Max.X; x++ { + c := color.NRGBAModel.Convert(im.At(x, y)).(color.NRGBA) + if c.A > 0 { + c.A = uint8(alpha) + } + dst.Set(x, y, c) + } + } + return encodePNG(path, dst) +} + +func encodePNG(path string, im image.Image) error { + dst, err := os.Create(path) + if err != nil { + return err + } + defer dst.Close() + return png.Encode(dst, im) +} + +func main() { + if err := run(); err != nil { + log.Fatal(err) + } +}