commit 7f593068f66aa8ad4b12905e52d99ae7193122ad
parent 332bd5f294994e1f47adc2f7264813d7b746004b
Author: Jack Mordaunt <jackmordaunt@gmail.com>
Date: Sun, 18 Feb 2018 16:04:50 +0100
[+] Encode direction based on input (icns -> png or png|jpg -> icns).
Diffstat:
1 file changed, 45 insertions(+), 12 deletions(-)
diff --git a/cmd/icnsify/main.go b/cmd/icnsify/main.go
@@ -2,6 +2,8 @@ package main
import (
"image"
+ "image/jpeg"
+ "image/png"
"io"
"log"
"os"
@@ -23,8 +25,8 @@ var (
func main() {
var (
- inputPath = pflag.StringP("input", "i", "", "Input image for conversion to icns (jpg|png)")
- outputPath = pflag.StringP("output", "o", "", "Output path, defaults to <path/to/image>.icns")
+ inputPath = pflag.StringP("input", "i", "", "Input image for conversion to icns from jpg|png or visa versa.")
+ outputPath = pflag.StringP("output", "o", "", "Output path, defaults to <path/to/image>.(icns|png) depending on input.")
resize = pflag.IntP("resize", "r", 5, "Quality of resize algorithm. Values range from 0 to 5, fastest to slowest execution time. Defaults to slowest for best quality.")
)
pflag.Parse()
@@ -52,13 +54,22 @@ func main() {
}
img, format, err := image.Decode(input)
if err != nil {
- log.Fatalf("decoding image: %v", err)
+ log.Fatalf("decoding input: %v", err)
}
- enc := icns.NewEncoder(output).
- WithAlgorithm(algorithm).
- WithFormat(format)
- if err := enc.Encode(img); err != nil {
- log.Fatalf("encoding icns: %v", err)
+ if format == "icns" {
+ imageType := strings.ToLower(filepath.Ext(out))
+ if _, ok := encoders[imageType]; !ok {
+ imageType = ".png"
+ }
+ if err := encoders[imageType](output, img); err != nil {
+ log.Fatalf("encoding %s: %v", imageType, err)
+ }
+ } else {
+ enc := icns.NewEncoder(output).
+ WithAlgorithm(algorithm)
+ if err := enc.Encode(img); err != nil {
+ log.Fatalf("encoding icns: %v", err)
+ }
}
}
@@ -67,11 +78,21 @@ func sanitiseInputs(
outputPath string,
resize int,
) (string, string, icns.InterpolationFunction) {
- if inputPath != "" && outputPath == "" {
- outputPath = changeExtensionTo(inputPath, "icns")
+ if filepath.Ext(inputPath) == ".icns" {
+ if outputPath == "" {
+ outputPath = changeExtensionTo(inputPath, "png")
+ }
+ if filepath.Ext(outputPath) == "" {
+ outputPath += ".png"
+ }
}
- if filepath.Ext(outputPath) == "" {
- outputPath += ".icns"
+ if filepath.Ext(inputPath) != ".icns" {
+ if outputPath == "" {
+ outputPath = changeExtensionTo(inputPath, "icns")
+ }
+ if filepath.Ext(outputPath) == "" {
+ outputPath += ".icns"
+ }
}
if resize < 0 {
resize = 0
@@ -88,3 +109,15 @@ func changeExtensionTo(path, ext string) string {
}
return filepath.Base(path[:len(path)-len(filepath.Ext(path))] + ext)
}
+
+type encoderFunc func(io.Writer, image.Image) error
+
+func encodeJPEG(w io.Writer, m image.Image) error {
+ return jpeg.Encode(w, m, &jpeg.Options{Quality: 100})
+}
+
+var encoders = map[string]encoderFunc{
+ ".png": png.Encode,
+ ".jpg": encodeJPEG,
+ ".jpeg": encodeJPEG,
+}