-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
image.go
243 lines (217 loc) · 6.08 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
package utils
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/Sora233/DDBOT/proxy_pool"
"github.com/Sora233/DDBOT/requests"
"github.com/ericpauley/go-quantize/quantize"
"github.com/nfnt/resize"
"image"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"io"
"strings"
"time"
)
func ImageGet(url string, prefer proxy_pool.Prefer, opt ...requests.Option) ([]byte, error) {
if url == "" {
return nil, errors.New("empty url")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer cancel()
opts := []requests.Option{requests.ProxyOption(prefer), requests.TimeoutOption(time.Second * 5)}
opts = append(opts, opt...)
resp, err := requests.Get(ctx, url, nil, 3, opts...)
if err != nil {
return nil, err
}
return resp.Content()
}
func ImageNormSize(origImage []byte) ([]byte, error) {
dImage, format, err := image.Decode(bytes.NewReader(origImage))
if err != nil {
return nil, fmt.Errorf("image decode failed %v", err)
}
resizedImage := resize.Thumbnail(1200, 1200, dImage, resize.Lanczos3)
resizedImageBuffer := bytes.NewBuffer(make([]byte, 0))
switch format {
case "jpeg":
err = jpeg.Encode(resizedImageBuffer, resizedImage, &jpeg.Options{Quality: 100})
case "gif":
err = gif.Encode(resizedImageBuffer, resizedImage, &gif.Options{
Quantizer: quantize.MedianCutQuantizer{},
})
case "png":
err = png.Encode(resizedImageBuffer, resizedImage)
default:
err = fmt.Errorf("unknown format %v", format)
}
return resizedImageBuffer.Bytes(), err
}
func ImageGetAndNorm(url string, prefer proxy_pool.Prefer) ([]byte, error) {
img, err := ImageGet(url, prefer)
if err != nil {
return img, err
}
img, err = ImageNormSize(img)
return img, err
}
func ImageFormat(origImage []byte) (string, error) {
_, format, err := image.DecodeConfig(bytes.NewReader(origImage))
return format, err
}
func ImageReserve(imgBytes []byte) ([]byte, error) {
st := time.Now()
defer func() {
ed := time.Now()
logger.WithField("FuncName", FuncName()).Tracef("cost %v", ed.Sub(st))
}()
format, err := ImageFormat(imgBytes)
if err != nil {
return nil, err
} else if format != "gif" {
return nil, errors.New("不是动图")
}
img, err := DecodeGifWithCompleteFrame(bytes.NewReader(imgBytes))
if err != nil {
return nil, err
}
length := len(img.Image)
for idx := range img.Image {
oidx := length - 1 - idx
if idx >= oidx {
break
}
tmp := img.Image[idx]
img.Image[idx] = img.Image[oidx]
img.Image[oidx] = tmp
}
var result = bytes.NewBuffer(nil)
err = gif.EncodeAll(result, img)
if err != nil {
return nil, err
}
return result.Bytes(), nil
}
func DecodeGifWithCompleteFrame(r io.Reader) (g *gif.GIF, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Error while decoding: %s", r)
}
}()
g, err = gif.DecodeAll(r)
if err != nil {
return nil, err
}
imgWidth, imgHeight := GetGifDimensions(g)
overpaintImage := image.NewRGBA(image.Rect(0, 0, imgWidth, imgHeight))
for index, srcImg := range g.Image {
switch g.Disposal[index] {
case gif.DisposalNone:
draw.Draw(overpaintImage, overpaintImage.Bounds(), srcImg, image.Point{}, draw.Over)
draw.Draw(srcImg, overpaintImage.Bounds(), overpaintImage, image.Point{}, draw.Src)
case gif.DisposalBackground:
// TODO is it correct?
//draw.Draw(overpaintImage, overpaintImage.Bounds(), srcImg, image.Point{}, draw.Src)
case gif.DisposalPrevious:
// TODO how?
draw.Draw(overpaintImage, overpaintImage.Bounds(), srcImg, image.Point{}, draw.Over)
draw.Draw(srcImg, overpaintImage.Bounds(), overpaintImage, image.Point{}, draw.Src)
}
}
return g, nil
}
func GetGifDimensions(gif *gif.GIF) (x, y int) {
var lowestX int
var lowestY int
var highestX int
var highestY int
for _, img := range gif.Image {
if img.Rect.Min.X < lowestX {
lowestX = img.Rect.Min.X
}
if img.Rect.Min.Y < lowestY {
lowestY = img.Rect.Min.Y
}
if img.Rect.Max.X > highestX {
highestX = img.Rect.Max.X
}
if img.Rect.Max.Y > highestY {
highestY = img.Rect.Max.Y
}
}
return highestX - lowestX, highestY - lowestY
}
func ImageSuffix(name string) bool {
for _, suf := range []string{"jpg", "png", "jpeg"} {
if strings.HasSuffix(name, suf) {
return true
}
}
return false
}
func MergeImages(images [][]byte) ([]byte, error) {
if len(images) == 0 {
return nil, errors.New("no image given")
}
// 1440可以被2 3 4 5 6整除
const ColumnSize = 1440
var columns int
for columns = 2; columns < 6 && columns*columns < len(images); columns++ {
}
var subImageSize = ColumnSize / columns
var rows = (len(images)-1)/columns + 1
for _, img := range images {
if len(img) == 0 {
return nil, errors.New("empty image exists")
}
}
var bg = image.NewNRGBA(image.Rect(0, 0, ColumnSize, subImageSize*rows))
draw.Draw(bg, bg.Bounds(), image.White, image.Point{}, draw.Src)
for i, imgBytes := range images {
cfg, _, err := image.DecodeConfig(bytes.NewReader(imgBytes))
if err != nil {
return nil, fmt.Errorf("DecodeConfig failed %v", err)
}
var minSize = cfg.Width
if minSize > cfg.Height {
minSize = cfg.Height
}
var Dx int
if cfg.Width > cfg.Height {
Dx = (cfg.Width - minSize) / 2
}
if Dx < 0 {
Dx = 0
}
img, _, err := image.Decode(bytes.NewReader(imgBytes))
if err != nil {
return nil, fmt.Errorf("Decode failed %v", err)
}
if cfg.Width == cfg.Height {
img = resize.Resize(uint(subImageSize), uint(subImageSize), img, resize.Lanczos3)
} else {
img = resize.Resize(uint(subImageSize), uint(subImageSize), SubImage(img, image.Rect(Dx, 0, minSize+Dx, minSize)), resize.Lanczos3)
}
si := i / columns
sj := i % columns
draw.Draw(bg, img.Bounds().Add(image.Point{X: sj * subImageSize, Y: si * subImageSize}), img, image.Point{}, draw.Src)
}
var result = new(bytes.Buffer)
err := jpeg.Encode(result, bg, &jpeg.Options{Quality: 100})
if err != nil {
return nil, err
}
resBytes := result.Bytes()
return resBytes, nil
}
func SubImage(img image.Image, r image.Rectangle) image.Image {
var bgSize = image.Rect(0, 0, r.Dx(), r.Dy())
var bg = image.NewNRGBA(bgSize)
draw.Draw(bg, bg.Bounds(), img, r.Min, draw.Src)
return bg
}