Debian Codegraph @

vendor/github.com/xyproto/gfx/file.go

raw
1 package gfx
2
3 import (
4 "encoding/json"
5 "image"
6 "io"
7 "os"
8 )
9
10 // SavePNG saves an image using the provided file name.
11 func SavePNG(fn string, src image.Image) error {
12 if src == nil || src.Bounds().Empty() {
13 return Error("SavePNG: empty image provided")
14 }
15
16 w, err := CreateFile(fn)
17 if err != nil {
18 return err
19 }
20 defer w.Close()
21
22 return EncodePNG(w, src)
23 }
24
25 // MustOpenImage decodes an image using the provided file name. Panics on error.
26 func MustOpenImage(fn string) image.Image {
27 m, err := OpenImage(fn)
28 if err != nil {
29 panic(err)
30 }
31
32 return m
33 }
34
35 // OpenImage decodes an image using the provided file name.
36 func OpenImage(fn string) (image.Image, error) {
37 r, err := OpenFile(fn)
38 if err != nil {
39 return nil, err
40 }
41 defer r.Close()
42
43 return DecodeImage(r)
44 }
45
46 // OpenFile opens the named file for reading.
47 func OpenFile(fn string) (*os.File, error) {
48 return os.Open(fn)
49 }
50
51 // CreateFile creates or truncates the named file.
52 func CreateFile(fn string) (*os.File, error) {
53 return os.Create(fn)
54 }
55
56 // ReadFile opens a file and calls the given ReadFunc.
57 func ReadFile(fn string, rf ReadFunc) error {
58 f, err := OpenFile(fn)
59 if err != nil {
60 return err
61 }
62 defer f.Close()
63
64 return rf(f)
65 }
66
67 // ReadJSON opens and decodes a JSON file.
68 func ReadJSON(fn string, v interface{}) error {
69 return ReadFile(fn, DecodeJSONFunc(v))
70 }
71
72 // ReadFunc is a func that takes a io.Reader and returns an error.
73 type ReadFunc func(r io.Reader) error
74
75 // DecodeJSONFunc returns a function that takes a reader, and decodes into the given value.
76 func DecodeJSONFunc(v interface{}) ReadFunc {
77 return func(r io.Reader) error {
78 return json.NewDecoder(r).Decode(v)
79 }
80 }