Refactor export functions

- Pass output path as parameter
- Return and handle errors correctly
This commit is contained in:
David Vogel 2023-12-22 11:03:04 +01:00
parent 0454e29e34
commit 182373d3cc
3 changed files with 18 additions and 12 deletions

View File

@ -1,16 +1,17 @@
package main package main
import ( import (
"fmt"
"image/jpeg" "image/jpeg"
"log" "log"
"os" "os"
) )
func exportJPEG(stitchedImage *StitchedImage) error { func exportJPEG(stitchedImage *StitchedImage, outputPath string) error {
log.Printf("Creating output file %q.", *flagOutputPath) log.Printf("Creating output file %q.", outputPath)
f, err := os.Create(*flagOutputPath) f, err := os.Create(outputPath)
if err != nil { if err != nil {
log.Panic(err) return fmt.Errorf("failed to create file: %w", err)
} }
defer f.Close() defer f.Close()
@ -19,7 +20,7 @@ func exportJPEG(stitchedImage *StitchedImage) error {
} }
if err := jpeg.Encode(f, stitchedImage, options); err != nil { if err := jpeg.Encode(f, stitchedImage, options); err != nil {
log.Panic(err) return fmt.Errorf("failed to encode image %q: %w", outputPath, err)
} }
return nil return nil

View File

@ -1,16 +1,17 @@
package main package main
import ( import (
"fmt"
"image/png" "image/png"
"log" "log"
"os" "os"
) )
func exportPNG(stitchedImage *StitchedImage) error { func exportPNG(stitchedImage *StitchedImage, outputPath string) error {
log.Printf("Creating output file %q.", *flagOutputPath) log.Printf("Creating output file %q.", outputPath)
f, err := os.Create(*flagOutputPath) f, err := os.Create(outputPath)
if err != nil { if err != nil {
log.Panic(err) return fmt.Errorf("failed to create file: %w", err)
} }
defer f.Close() defer f.Close()
@ -19,7 +20,7 @@ func exportPNG(stitchedImage *StitchedImage) error {
} }
if err := encoder.Encode(f, stitchedImage); err != nil { if err := encoder.Encode(f, stitchedImage); err != nil {
log.Panic(err) return fmt.Errorf("failed to encode image %q: %w", outputPath, err)
} }
return nil return nil

View File

@ -269,9 +269,13 @@ func main() {
fileExtension := strings.ToLower(filepath.Ext(*flagOutputPath)) fileExtension := strings.ToLower(filepath.Ext(*flagOutputPath))
switch fileExtension { switch fileExtension {
case ".png": case ".png":
exportPNG(stitchedImage) if err := exportPNG(stitchedImage, *flagOutputPath); err != nil {
log.Panicf("Export of PNG file failed: %v", err)
}
case ".jpg", ".jpeg": case ".jpg", ".jpeg":
exportJPEG(stitchedImage) if err := exportJPEG(stitchedImage, *flagOutputPath); err != nil {
log.Panicf("Export of JPEG file failed: %v", err)
}
default: default:
log.Panicf("Unknown output format %q.", fileExtension) log.Panicf("Unknown output format %q.", fileExtension)
} }