-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage.go
More file actions
103 lines (92 loc) · 2.17 KB
/
Copy pathimage.go
File metadata and controls
103 lines (92 loc) · 2.17 KB
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
//
// resize.go
//
// Created by Frederic DELBOS - fred@hyperboloide.com on Feb 8 2015.
// This file is subject to the terms and conditions defined in
// file 'LICENSE', which is part of this source code package.
//
package sprocess
import (
"errors"
"fmt"
"github.com/nfnt/resize"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
)
type ImageOperation int
const (
ImageThumbnail ImageOperation = iota
ImageResize
)
type Image struct {
Operation ImageOperation
Height uint
Width uint
Interpolation string
Output string
interpolation resize.InterpolationFunction
Name string
}
func (i *Image) GetName() string {
return i.Name
}
func (i *Image) Start() error {
switch i.Operation {
case ImageThumbnail:
if i.Height == 0 || i.Width == 0 {
return errors.New("height and width cannot be equal to 0")
}
case ImageResize:
if i.Height == 0 && i.Width == 0 {
return errors.New("height and width cannot be both equal to 0")
}
default:
return errors.New("invalid image operation")
}
switch i.Interpolation {
case "", "NearestNeighbor":
i.interpolation = resize.NearestNeighbor
case "Bilinear":
i.interpolation = resize.Bilinear
case "Bicubic":
i.interpolation = resize.Bicubic
case "MitchellNetravali":
i.interpolation = resize.MitchellNetravali
case "Lanczos2":
i.interpolation = resize.Lanczos2
case "Lanczos3":
i.interpolation = resize.Lanczos3
default:
return errors.New(fmt.Sprintf("unknow interpolation algorithm '%s'", i.Interpolation))
}
switch i.Output {
case "", "jpg", "png", "gif":
default:
return errors.New(fmt.Sprintf("unsuported output format '%s'", i.Output))
}
return nil
}
func (i *Image) Encode(r io.Reader, w io.Writer, d *Data) error {
img, _, err := image.Decode(r)
if err != nil {
return err
}
var newImage image.Image
if i.Operation == ImageResize {
newImage = resize.Resize(i.Width, i.Height, img, i.interpolation)
} else {
newImage = resize.Thumbnail(i.Width, i.Height, img, i.interpolation)
}
switch i.Output {
case "jpg", "":
err = jpeg.Encode(w, newImage, nil)
case "png":
err = png.Encode(w, newImage)
case "gif":
err = gif.Encode(w, newImage, nil)
}
return err
}