forked from signintech/gopdf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_holder.go
81 lines (69 loc) · 1.39 KB
/
image_holder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package gopdf
import (
"bytes"
"crypto/md5"
"fmt"
"io"
"os"
)
// ImageHolder hold image data
type ImageHolder interface {
ID() string
io.Reader
}
// ImageHolderByBytes create ImageHolder by []byte
func ImageHolderByBytes(b []byte) (ImageHolder, error) {
return newImageBuff(b)
}
// ImageHolderByPath create ImageHolder by image path
func ImageHolderByPath(path string) (ImageHolder, error) {
return newImageBuffByPath(path)
}
// ImageHolderByReader create ImageHolder by io.Reader
func ImageHolderByReader(r io.Reader) (ImageHolder, error) {
return newImageBuffByReader(r)
}
// imageBuff image holder (impl ImageHolder)
type imageBuff struct {
id string
bytes.Buffer
}
func newImageBuff(b []byte) (*imageBuff, error) {
h := md5.New()
_, err := h.Write(b)
if err != nil {
return nil, err
}
var i imageBuff
i.id = fmt.Sprintf("%x", h.Sum(nil))
i.Write(b)
return &i, nil
}
func newImageBuffByPath(path string) (*imageBuff, error) {
var i imageBuff
i.id = path
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
i.Write(b)
return &i, nil
}
func newImageBuffByReader(r io.Reader) (*imageBuff, error) {
b, err := io.ReadAll(r)
if err != nil {
return nil, err
}
h := md5.New()
_, err = h.Write(b)
if err != nil {
return nil, err
}
var i imageBuff
i.id = fmt.Sprintf("%x", h.Sum(nil))
i.Write(b)
return &i, nil
}
func (i *imageBuff) ID() string {
return i.id
}