74 lines
1.3 KiB
Go
74 lines
1.3 KiB
Go
|
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)
|
||
|
}
|
||
|
}
|