Added tool to change alpha layer of image.

This commit is contained in:
Sander Schobers 2020-05-09 22:50:29 +02:00
parent 72da0ef462
commit b9515823d3

73
cmd/imadapt/imadapt.go Normal file
View File

@ -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)
}
}