Add Save and Load util function
This commit is contained in:
parent
93abbc2231
commit
146e6d6c8e
1 changed files with 46 additions and 0 deletions
46
fileutil.go
Normal file
46
fileutil.go
Normal file
|
@ -0,0 +1,46 @@
|
|||
package draw2d
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"image"
|
||||
"image/png"
|
||||
"os"
|
||||
)
|
||||
|
||||
// SaveToPngFile create and save an image to a file using PNG format
|
||||
func SaveToPngFile(filePath string, m image.Image) error {
|
||||
// Create the file
|
||||
f, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
// Create Writer from file
|
||||
b := bufio.NewWriter(f)
|
||||
// Write the image into the buffer
|
||||
err = png.Encode(b, m)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = b.Flush()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadFromPngFile Open a png file
|
||||
func LoadFromPngFile(filePath string) (image.Image, error) {
|
||||
// Open file
|
||||
f, err := os.OpenFile(filePath, 0, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
b := bufio.NewReader(f)
|
||||
img, err := png.Decode(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return img, nil
|
||||
}
|
Loading…
Reference in a new issue