tins2020/cmd/imadapt/imadapt.go

111 lines
2.2 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 of '%s'; error: %v", path, err)
}
}
case "gray":
flags := flag.NewFlagSet("gray", flag.ContinueOnError)
flags.Parse(args[1:])
for _, path := range flags.Args() {
err := gray(path)
if err != nil {
return fmt.Errorf("couldn't convert to grayscale of '%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 gray(path string) 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.NewRGBA(bounds)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
c := im.At(x, y)
rgba := color.NRGBAModel.Convert(c).(color.NRGBA)
if rgba.A > 0 {
gray := color.GrayModel.Convert(c).(color.Gray)
rgba.R, rgba.G, rgba.B = gray.Y, gray.Y, gray.Y
dst.Set(x, y, rgba)
} else {
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)
}
}