forked from andreaskoch/allmark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resizer.go
111 lines (77 loc) · 1.94 KB
/
resizer.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
// Copyright 2014 Andreas Koch. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package imageconversion
import (
"fmt"
"github.com/nfnt/resize"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"strings"
)
func MimeTypeIsSupported(mimeType string) bool {
switch mimeType {
case "image/png", "image/jpeg", "image/gif":
return true
default:
return false
}
panic("Unreachable")
}
func GetFileExtensionFromMimeType(mimeType string) string {
switch mimeType {
case "image/png":
return "png"
case "image/jpeg":
return "jpg"
case "image/gif":
return "gif"
default:
return strings.ToLower(strings.Replace(mimeType, "image/", "", 1))
}
panic("Unreachable")
}
func Resize(source io.Reader, mimeType string, width, height uint, target io.Writer) error {
// check the mime type
if !MimeTypeIsSupported(mimeType) {
return fmt.Errorf("The mime-type %q is currently not supported.", mimeType)
}
// read the source image
img, err := decode(source, mimeType)
if err != nil {
return err
}
// resize the source image
thumb := resize.Thumbnail(width, height, img, resize.Lanczos3)
// write the thumbnail to the target
return encode(mimeType, thumb, target)
}
func encode(mimeType string, thumb image.Image, target io.Writer) error {
switch mimeType {
case "image/png":
return png.Encode(target, thumb)
case "image/jpeg":
return jpeg.Encode(target, thumb, nil)
case "image/gif":
return gif.Encode(target, thumb, nil)
default:
return fmt.Errorf("Unsupported mime type %s", mimeType)
}
panic("Unreachable")
}
func decode(source io.Reader, mimeType string) (image.Image, error) {
switch mimeType {
case "image/png":
return png.Decode(source)
case "image/jpeg":
return jpeg.Decode(source)
case "image/gif":
return gif.Decode(source)
default:
return nil, fmt.Errorf("Unsupported mime type %s", mimeType)
}
panic("Unreachable")
}