-
Notifications
You must be signed in to change notification settings - Fork 0
/
processing.go
81 lines (67 loc) · 1.67 KB
/
processing.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 image
import (
"github.com/disintegration/imaging"
"github.com/pkg/errors"
imglib "image"
"io"
"net/http"
"os"
"strings"
)
type (
Processing interface {
Resize(width, length uint) imglib.Image
Image() imglib.Image
}
processing struct {
img imglib.Image
imgFile *os.File
}
)
func Load(path string) (*processing, error) {
var (
imgFile *os.File
err error
)
defer imgFile.Close()
if strings.Contains(path, "http") {
// load image from URL, then download it first
splitPath := strings.Split(path, "/")
fileName := splitPath[len(splitPath)-1]
questionMarkIndex := strings.Index(fileName, "?")
fileName = fileName[:questionMarkIndex]
imgFile, err = os.Create(fileName)
if err != nil {
return nil, errors.Wrap(err, "phastos.go.image.processing.Load.CreateNewFile")
}
defer os.RemoveAll(fileName)
res, err := http.Get(path)
if err != nil {
return nil, errors.Wrap(err, "phastos.go.image.processing.Load.GetImage")
}
defer res.Body.Close()
_, err = io.Copy(imgFile, res.Body)
if err != nil {
return nil, errors.Wrap(err, "phastos.go.image.processing.Load.CopyContentToNewFile")
}
path = fileName
}
imgFile, err = os.Open(path)
if err != nil {
return nil, errors.Wrap(err, "phastos.go.image.processing.Load.OpenFile")
}
img, _, err := imglib.Decode(imgFile)
if err != nil {
return nil, errors.Wrap(err, "phastos.go.helper.image.LoadImage.ImageDecode")
}
return &processing{
imgFile: imgFile,
img: img,
}, nil
}
func (p *processing) Resize(width, length int) imglib.Image {
return imaging.Resize(p.img, width, length, imaging.Lanczos)
}
func (p *processing) Image() imglib.Image {
return p.img
}