59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"math"
|
|
"image"
|
|
"image/draw"
|
|
"image/jpeg"
|
|
"image/png"
|
|
"path/filepath"
|
|
"strings"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
func avgColor(orig, upd int) int {
|
|
a := float64(orig * orig)
|
|
b := float64(upd * upd)
|
|
return int(math.Sqrt(float64((a + b)/2)))
|
|
}
|
|
|
|
func loadImage(path string) (*image.RGBA, string) {
|
|
f, err := os.Open(path)
|
|
defer f.Close()
|
|
if err != nil {
|
|
panic(fmt.Sprintf("File access error: Unable to open image at path %q", path))
|
|
}
|
|
img, format, err := image.Decode(f)
|
|
rect := img.Bounds()
|
|
rgba := image.NewRGBA(rect)
|
|
draw.Draw(rgba, rect, img, rect.Min, draw.Src)
|
|
|
|
return rgba, format
|
|
}
|
|
|
|
func saveImage(iPath, filterName, encodeType string, img *image.RGBA) {
|
|
ext := filepath.Ext(iPath)
|
|
name := strings.TrimSuffix(filepath.Base(iPath), ext)
|
|
newImagePath := fmt.Sprintf("%s/%s_%s%s", filepath.Dir(iPath), name, filterName, ext)
|
|
fg, err := os.Create(newImagePath)
|
|
defer fg.Close()
|
|
if err != nil {
|
|
panic(fmt.Sprintf("File access error: Unable to save image to path %q", newImagePath))
|
|
}
|
|
|
|
if encodeType == "jpeg" {
|
|
err = jpeg.Encode(fg, img, nil)
|
|
if err != nil {
|
|
panic("Encode error: Unable to encode output as jpeg")
|
|
}
|
|
} else if encodeType == "png" {
|
|
err = png.Encode(fg, img)
|
|
if err != nil {
|
|
panic("Encode error: Unable to encode output as png")
|
|
}
|
|
} else {
|
|
panic(fmt.Sprintf("Encode error: Unable to encode output to unsupported format %q", encodeType))
|
|
}
|
|
}
|