Hochwasser/render/image.go

73 lines
1.5 KiB
Go
Raw Permalink Normal View History

2020-02-14 22:29:58 +01:00
package render
import (
"image"
2020-02-15 13:58:01 +01:00
"image/color"
2020-02-14 22:29:58 +01:00
_ "image/gif" // register gif, jpeg, png format handlers
_ "image/jpeg"
"image/png"
"os"
"golang.org/x/image/draw"
)
2020-12-31 17:42:53 +01:00
func ReadImage(path string) (*image.NRGBA, error) {
2020-02-14 22:29:58 +01:00
reader, err := os.Open(path)
if err != nil {
return nil, err
}
img, _, err := image.Decode(reader)
if err != nil {
return nil, err
}
2020-12-31 17:42:53 +01:00
return imgToNRGBA(img), nil
2020-02-14 22:29:58 +01:00
}
func WriteImage(path string, img image.Image) error {
f, err := os.Create(path)
if err != nil {
return err
}
if err := png.Encode(f, img); err != nil {
f.Close()
return err
}
return nil
}
2020-12-31 17:42:53 +01:00
func imgToNRGBA(img image.Image) *image.NRGBA {
2020-02-14 22:29:58 +01:00
b := img.Bounds()
r := image.NewNRGBA(b)
for x := b.Min.X; x < b.Max.X; x++ {
for y := b.Min.Y; y < b.Max.Y; y++ {
r.Set(x, y, img.At(x, y))
}
}
return r
}
2020-12-28 00:58:50 +01:00
// ImgColorFilter replaces `from` with `to` in `img`, and sets all other pixels
// to color.Transparent
func ImgColorFilter(img *image.NRGBA, from, to color.NRGBA) *image.NRGBA {
2020-02-15 13:58:01 +01:00
b := img.Bounds()
r := image.NewNRGBA(b)
for x := b.Min.X; x < b.Max.X; x++ {
for y := b.Min.Y; y < b.Max.Y; y++ {
if img.At(x, y) == from {
r.SetNRGBA(x, y, to)
2020-12-28 00:58:50 +01:00
} else {
r.Set(x, y, color.Transparent)
2020-02-15 13:58:01 +01:00
}
}
}
return r
}
2020-02-14 22:29:58 +01:00
func ScaleImage(img image.Image, factor int) (scaled *image.NRGBA) {
b := img.Bounds()
scaledBounds := image.Rect(0, 0, b.Max.X*factor, b.Max.Y*factor)
scaledImg := image.NewNRGBA(scaledBounds)
draw.NearestNeighbor.Scale(scaledImg, scaledBounds, img, b, draw.Src, nil)
return scaledImg
}