aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--convert.go101
-rw-r--r--go.mod5
-rw-r--r--go.sum2
4 files changed, 109 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..896533f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+/convert
diff --git a/convert.go b/convert.go
new file mode 100644
index 0000000..ea7403c
--- /dev/null
+++ b/convert.go
@@ -0,0 +1,101 @@
+package main
+
+import (
+ "errors"
+ "flag"
+ "fmt"
+ "image"
+ "image/gif"
+ "image/jpeg"
+ "image/png"
+ "os"
+ "strings"
+
+ "golang.org/x/image/bmp"
+ "golang.org/x/image/tiff"
+ _ "golang.org/x/image/webp"
+)
+
+func load(filename string) (image.Image, error) {
+ file := os.Stdin
+ if filename != "-" {
+ var err error
+ file, err = os.Open(filename)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ }
+
+ img, _, err := image.Decode(file)
+ if err != nil {
+ return nil, fmt.Errorf("decode %q: %s", filename, err)
+ }
+
+ return img, nil
+}
+
+func run() error {
+ args := flag.Args()
+ if len(args) != 2 {
+ return errors.New("usage: convert input-file output-file")
+ }
+ inputFileName, outputFileName := args[0], args[1]
+
+ n := strings.LastIndex(outputFileName, ".")
+ if n < 0 {
+ return errors.New("unknown output file extension")
+ }
+ ext := outputFileName[n+1:]
+ switch ext {
+ case "gif", "jpeg", "jpg", "png", "bmp", "tiff":
+ default:
+ return fmt.Errorf("unknown output file extension %q", ext)
+ }
+
+ input, err := load(inputFileName)
+ if err != nil {
+ return err
+ }
+
+ outputFile, err := os.Create(outputFileName)
+ if err != nil {
+ return err
+ }
+ defer outputFile.Close()
+ switch ext {
+ case "gif":
+ err = gif.Encode(outputFile, input, nil)
+ case "jpeg", "jpg":
+ err = jpeg.Encode(outputFile, input, nil)
+ case "png":
+ err = png.Encode(outputFile, input)
+ case "bmp":
+ err = bmp.Encode(outputFile, input)
+ case "tiff":
+ err = tiff.Encode(outputFile, input, nil)
+ }
+ if err != nil {
+ return err
+ }
+ return outputFile.Close()
+}
+
+func main() {
+ flag.Usage = func() {
+ fmt.Fprint(os.Stderr, `Usage: convert input-file output-file
+Supported formats:
+ png
+ jpeg
+ bmp
+ tiff
+ webp (input only)
+`)
+ }
+ flag.Parse()
+
+ if err := run(); err != nil {
+ fmt.Fprintf(os.Stderr, "convert: %s\n", err)
+ os.Exit(1)
+ }
+}
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..36ddbeb
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,5 @@
+module gitlab.com/rhogenson/convert
+
+go 1.24.1
+
+require golang.org/x/image v0.25.0
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..9865c76
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,2 @@
+golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
+golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=