/
png.go
119 lines (104 loc) · 2.46 KB
/
png.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package images
import (
"bytes"
"fmt"
"image"
"image/draw"
"image/png"
"io"
"slices"
"strings"
)
// Png struct implements the File and Image interface from the files pkg.
type Png struct {
compatibleFormats map[string][]string
compatibleMIMETypes map[string][]string
}
// NewPng returns a pointer to a Png instance.
// The Png object is set with a map with list of supported file formats.
func NewPng() *Png {
p := Png{
compatibleFormats: map[string][]string{
"Image": {
JPG,
JPEG,
GIF,
WEBP,
TIFF,
BMP,
},
"Document": {
PDF,
},
},
compatibleMIMETypes: map[string][]string{
"Image": {
JPG,
JPEG,
GIF,
WEBP,
TIFF,
BMP,
},
"Document": {
PDF,
},
},
}
return &p
}
// SupportedFormats returns a map with a slice of supported files.
// Every key of the map represents the kind of a file.
func (p *Png) SupportedFormats() map[string][]string {
return p.compatibleFormats
}
// SupportedMIMETypes returns a map with a slice of supported MIME types.
func (p *Png) SupportedMIMETypes() map[string][]string {
return p.compatibleMIMETypes
}
// ConvertTo method converts a given file to a target format.
// This method returns a file in form of a slice of bytes.
func (p *Png) ConvertTo(fileType, subType string, file io.Reader) (io.Reader, error) {
var result []byte
compatibleFormats, ok := p.SupportedFormats()[fileType]
if !ok {
return nil, fmt.Errorf("ConvertTo: file type not supported: %s", fileType)
}
if !slices.Contains(compatibleFormats, subType) {
return nil, fmt.Errorf("ConvertTo: file sub-type not supported: %s", subType)
}
switch strings.ToLower(fileType) {
case imageType:
img, err := png.Decode(file)
if err != nil {
return nil, err
}
result, err = convertToImage(subType, img)
if err != nil {
return nil, fmt.Errorf(
"ConvertTo: error at converting image to another format: %w",
err,
)
}
case documentType:
img, err := png.Decode(file)
if err != nil {
return nil, err
}
rgba := image.NewRGBA(img.Bounds())
draw.Draw(rgba, img.Bounds(), img, image.Point{}, draw.Src)
result, err = convertToDocument(subType, rgba)
if err != nil {
return nil, fmt.Errorf(
"ConvertTo: error at converting image to another format: %w",
err,
)
}
}
return bytes.NewReader(result), nil
}
// ImageType returns the file format of the current image.
// This method implements the Image interface.
func (p *Png) ImageType() string {
return PNG
}