-
Notifications
You must be signed in to change notification settings - F 8000 ork 0
/
Copy pathimage.go
91 lines (84 loc) · 2.23 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
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lcd
import (
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"math"
"net/http"
"os"
"github.com/fogleman/gg"
)
// Save the image, using the suffix to select the type of image.
func SaveImage(name string, img image.Image) error {
if len(name) < 3 {
return fmt.Errorf("%s: name must have suffix (jpg, png, gif)", name)
}
of, err := os.Create(name)
if err != nil {
return err
}
defer of.Close()
switch name[len(name)-3:] {
case "png":
return png.Encode(of, img)
case "jpg":
return jpeg.Encode(of, img, nil)
case "gif":
return gif.Encode(of, img, nil)
default:
return fmt.Errorf("%s: unknown image format", name)
}
}
// Rotate the image, using a max sized canvas.
func RotateImage(image image.Image, angle float64) image.Image {
if angle == 0 {
return image
}
// Create a canvas of the maximum size required.
dx := float64(image.Bounds().Dx())
dy := float64(image.Bounds().Dy())
size := int(math.Sqrt(dx*dx + dy*dy))
c := gg.NewContext(size, size)
width := image.Bounds().Dx()
height := image.Bounds().Dy()
startx := (size - width) / 2
starty := (size - height) / 2
c.RotateAbout(gg.Radians(angle), float64(size/2), float64(size/2))
c.DrawImage(image, startx, starty)
return c.Image()
}
// Get an image from the source URL.
func GetImage(src string) (image.Image, error) {
res, err := http.Get(src)
if err != nil {
return nil, err
}
img, _, err := image.Decode(res.Body)
res.Body.Close()
return img, err
}
// Read an image from a file.
func ReadImage(name string) (image.Image, error) {
inf, err := os.Open(name)
if err != nil {
return nil, err
}
defer inf.Close()
in, _, err := image.Decode(inf)
return in, err
}