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
import (
"fmt"
"image/jpeg"
"log"
"os"
)
func exportJPEG(stitchedImage *StitchedImage) error {
log.Printf("Creating output file %q.", *flagOutputPath)
f, err := os.Create(*flagOutputPath)
func exportJPEG(stitchedImage *StitchedImage, outputPath string) error {
log.Printf("Creating output file %q.", outputPath)
f, err := os.Create(outputPath)
if err != nil {
log.Panic(err)
return fmt.Errorf("failed to create file: %w", err)
}
defer f.Close()
@ -19,7 +20,7 @@ func exportJPEG(stitchedImage *StitchedImage) error {
}
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

View File

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

View File

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