github.com/pavlo67/common@v0.5.3/common/pnglib/files.go (about) 1 package pnglib 2 3 import ( 4 "image" 5 "image/png" 6 "os" 7 "path/filepath" 8 9 "github.com/pkg/errors" 10 11 "github.com/pavlo67/common/common/filelib" 12 ) 13 14 const onSave = "on pnglib.Save()" 15 16 func Save(img image.Image, filename string) error { 17 18 if img == nil { 19 return errors.New("img == nil / " + onSave) 20 } 21 22 if path := filepath.Dir(filename); path != "" && path != "." && path != ".." { 23 if _, err := filelib.Dir(path); err != nil { 24 return errors.Wrapf(err, "can't create dir '%s' / "+onSave, path) 25 } 26 } 27 28 resFile, err := os.Create(filename) 29 if err != nil { 30 return errors.Wrap(err, onSave) 31 } 32 defer resFile.Close() 33 34 if err = png.Encode(resFile, img); err != nil { 35 return errors.Wrap(err, onSave) 36 } 37 return nil 38 }