-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathimage.go
417 lines (356 loc) · 9.35 KB
/
image.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
package imgo
import (
"fmt"
"github.com/BurntSushi/graphics-go/graphics"
cliColor "github.com/fatih/color"
"github.com/golang/freetype"
"github.com/nfnt/resize"
"golang.org/x/image/bmp"
"golang.org/x/image/font"
"golang.org/x/image/tiff"
"image"
"image/color"
"image/draw"
"image/jpeg"
"image/png"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"runtime"
"strings"
)
type Image struct {
Error error
image *image.RGBA // the image
width int // image width
height int // image height
extension string // image extension
mimetype string // image mimetype
filesize int64 // image filesize
isGrayscale bool // is grayscale image
}
// ToImage returns the instance of image.Image of the image.
func (i Image) ToImage() image.Image {
return i.image
}
// String returns the image as a string.
func (i Image) String() string {
return fmt.Sprintf("Extension: %v\nMimetype: %v\nWidth: %v\nHeight: %v\n", i.extension, i.mimetype, i.width, i.height)
}
// addError adds an error to imgo.
// if OnlyReason is true, only the error message is returned.
func (i *Image) addError(err error, OnlyReason ...bool) {
log.SetPrefix("[IMGO] ")
var onlyReason bool
if len(OnlyReason) > 0 {
onlyReason = OnlyReason[0]
}
yellow := cliColor.New(cliColor.FgYellow).SprintFunc()
magenta := cliColor.New(cliColor.FgMagenta).SprintFunc()
_, file, line, ok := runtime.Caller(1)
if i.Error == nil {
if ok && !onlyReason {
i.Error = fmt.Errorf("%v %v", yellow(file, ":", line), magenta("Error: ", err.Error()))
} else {
i.Error = err
}
} else if err != nil {
if ok && !onlyReason {
i.Error = fmt.Errorf("%v\n%v %v", i.Error, yellow(file, ":", line), magenta("Error: ", err.Error()))
} else {
i.Error = fmt.Errorf("%v\n%v", i.Error, err)
}
}
}
// Extension returns the extension of the image.
func (i Image) Extension() string {
return i.extension
}
// Mimetype returns the mimetype of the image.
func (i Image) Mimetype() string {
return i.mimetype
}
// Height returns the height of the image.
func (i Image) Height() int {
return i.height
}
// Width returns the width of the image.
func (i Image) Width() int {
return i.width
}
// Filesize returns the filesize of the image, if instance is initiated from an actual file.
func (i Image) Filesize() int64 {
return i.filesize
}
// Bounds returns the bounds of the image.
func (i Image) Bounds() image.Rectangle {
return i.image.Bounds()
}
// Insert inserts source into the image at given (x, y) coordinate.
// source can be a file path, a URL, a base64 encoded string, an *os.File, an image.Image,
// a byte slice or an *Image.
func (i *Image) Insert(source interface{}, x, y int) *Image {
// the image to insert
insert := &Image{}
switch source.(type) {
case *Image:
insert = source.(*Image)
default:
insert = Load(source)
}
// check errors
if insert.Error != nil {
i.addError(insert.Error, true)
return i
}
if i.Error != nil {
return i
}
// check x and y is within the image
if x > i.width || y > i.height {
return i
}
// insert the image
draw.Draw(i.image, i.Bounds(), insert.image, insert.image.Bounds().Min.Sub(image.Pt(x, y)), draw.Over)
return i
}
// Save saves the image to the specified path.
// Only png, jpeg, jpg, tiff and bmp extensions are supported.
// path is the path the image will be saved to.
// quality is the quality of the image, between 1 and 100, default is 100, and is only used for jpeg images.
func (i *Image) Save(path string, quality ...int) *Image {
if i.Error != nil {
log.Println(i.Error)
return i
}
// check extension
pathSplit := strings.Split(path, ".")
extension := pathSplit[len(pathSplit)-1]
if !(extension == "png" || extension == "jpg" || extension == "jpeg" || extension == "tiff" || extension == "bmp") {
i.addError(ErrSaveImageFormatNotSupport)
log.Println(i.Error)
return i
}
// create file
file, err := os.Create(path)
if err != nil {
i.addError(err)
log.Println(i.Error)
return i
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Println(err)
}
}(file)
// get the image
var img image.Image
if i.isGrayscale { // grayscale image
gray := image.NewGray(i.image.Bounds())
for x := 0; x < i.width; x++ {
for y := 0; y < i.height; y++ {
rgbColor := i.image.At(x, y)
grayColor := gray.ColorModel().Convert(rgbColor)
gray.Set(x, y, grayColor)
}
}
img = gray
} else { // RGBA image
img = i.image
}
// save image to file
if extension == "png" {
err = png.Encode(file, img)
} else if extension == "jpg" || extension == "jpeg" {
if len(quality) > 0 && quality[0] > 0 && quality[0] < 100 {
err = jpeg.Encode(file, img, &jpeg.Options{Quality: quality[0]})
} else {
err = jpeg.Encode(file, img, &jpeg.Options{Quality: 100})
}
} else if extension == "tiff" {
err = tiff.Encode(file, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
} else if extension == "bmp" {
err = bmp.Encode(file, img)
}
if err != nil {
i.addError(err)
log.Println(i.Error)
return i
}
return i
}
// Resize resizes the image to the specified width and height.
func (i *Image) Resize(width, height int) *Image {
if i.Error != nil {
return i
}
if width == i.width || height == i.height || (width == 0 && height == 0) {
return i
}
resized := resize.Resize(uint(width), uint(height), i.image, resize.Lanczos3)
i.image = Image2RGBA(resized)
i.width = resized.Bounds().Dx()
i.height = resized.Bounds().Dy()
return i
}
// Crop Cut out a rectangular part of the current image with given width and height.
func (i *Image) Crop(x, y, width, height int) *Image {
if i.Error != nil {
return i
}
if width == i.width || height == i.height || width == 0 || height == 0 || x > i.width || y > i.height {
return i
}
x1 := x + width
y1 := y + height
clipped := i.image.SubImage(image.Rect(x, y, x1, y1))
i.image = Image2RGBA(clipped)
i.width = width
i.height = height
return i
}
// Rotate rotates the image clockwise by the specified angle.
func (i *Image) Rotate(angle int) *Image {
if i.Error != nil {
return i
}
angle %= 360
if angle == 0 {
return i
}
// angle to radian
radian := float64(angle) * math.Pi / 180.0
cos := math.Cos(radian)
sin := math.Sin(radian)
w := float64(i.width)
h := float64(i.height)
// calculate the new image size
W := int(math.Max(math.Abs(w*cos-h*sin), math.Abs(w*cos+h*sin)))
H := int(math.Max(math.Abs(w*sin-h*cos), math.Abs(w*sin+h*cos)))
// rotate the image
dst := image.NewRGBA(image.Rect(0, 0, W, H))
err := graphics.Rotate(dst, i.image, &graphics.RotateOptions{Angle: radian})
if err != nil {
i.addError(err)
return i
}
i.image = dst
i.width = W
i.height = H
return i
}
// Grayscale converts the image to grayscale.
func (i *Image) Grayscale() *Image {
if i.Error != nil {
return i
}
for x := 0; x < i.width; x++ {
for y := 0; y < i.height; y++ {
rgbColor := i.image.At(x, y)
grayColor := color.GrayModel.Convert(rgbColor)
i.image.Set(x, y, grayColor)
}
}
i.isGrayscale = true
return i
}
// Flip mirror the image vertically or horizontally.
func (i *Image) Flip(flipType FlipType) *Image {
if i.Error != nil {
return i
}
if flipType == Horizontal {
i.flipHorizontally()
} else if flipType == Vertical {
i.flipVertically()
}
return i
}
// flipHorizontally flips the image horizontally.
func (i *Image) flipHorizontally() {
for x := 0; x < i.width/2; x++ {
for y := 0; y < i.height; y++ {
pixel := i.image.At(x, y)
i.image.Set(x, y, i.image.At(i.width-x-1, y))
i.image.Set(i.width-x-1, y, pixel)
}
}
}
// flipVertically flips the image vertically.
func (i *Image) flipVertically() {
for y := 0; y < i.height/2; y++ {
for x := 0; x < i.width; x++ {
pixel := i.image.At(x, y)
i.image.Set(x, y, i.image.At(x, i.height-y-1))
i.image.Set(x, i.height-y-1, pixel)
}
}
}
// Text write a text string to the image at given (x, y) coordinate.
func (i *Image) Text(label string, x, y int, fontPath string, fontColor color.Color, fontSize float64, dpi float64) *Image {
if i.Error != nil {
return i
}
// Load font
fontBytes, err := ioutil.ReadFile(fontPath)
if err != nil {
i.addError(err)
return i
}
myFont, err := freetype.ParseFont(fontBytes)
if err != nil {
i.addError(err)
return i
}
c := freetype.NewContext()
c.SetDPI(dpi)
c.SetFont(myFont)
c.SetFontSize(fontSize)
c.SetClip(i.Bounds())
c.SetDst(i.image)
uni := image.NewUniform(fontColor)
c.SetSrc(uni)
c.SetHinting(font.HintingNone)
// Draw text
pt := freetype.Pt(x, y+int(c.PointToFixed(fontSize)>>6))
if _, err := c.DrawString(label, pt); err != nil {
i.addError(err)
return i
}
return i
}
// Thumbnail returns a thumbnail of the image with given width and height.
func (i *Image) Thumbnail(width, height int) *Image {
if i.Error != nil {
return i
}
if width >= i.width || height >= i.height || width == 0 || height == 0 {
return i
}
dst := image.NewRGBA(image.Rect(0, 0, width, height))
err := graphics.Thumbnail(dst, i.image)
if err != nil {
i.addError(err)
return i
}
i.image = dst
i.width = width
i.height = height
return i
}
// HttpHandler responds the image as an HTTP handler.
func (i Image) HttpHandler(w http.ResponseWriter, r *http.Request) {
if i.Error != nil {
log.Println(i.Error)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "image/png")
err := png.Encode(w, i.image)
if err != nil {
log.Println(err)
}
}