-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgreenyfy.go
122 lines (87 loc) · 2.94 KB
/
greenyfy.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
package greenyfy
import (
"bytes"
"net/http"
"math"
"image"
"image/jpeg"
_ "image/png"
"image/draw"
"strconv"
"github.com/nfnt/resize"
"appengine"
"appengine/urlfetch"
"code.google.com/p/graphics-go/graphics"
)
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
img_url := r.FormValue("me")
if len(img_url) == 0 {
http.Redirect(w, r, "/index.html", 307)
return
}
c := appengine.NewContext(r)
c.Infof("Host: %v", appengine.DefaultVersionHostname(c))
item, err := getCached(c, img_url, do)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/jpeg")
w.Header().Set("Content-Length", strconv.Itoa(len(item.Value)))
if _, err := w.Write(item.Value); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func do (c appengine.Context, key string) (*bytes.Buffer, error) {
client := urlfetch.Client(c)
resp, err := client.Get(key)
if err != nil {
return nil, err
}
defer resp.Body.Close()
c.Infof("HTTP GET returned status %v", resp.Status)
img, _, err := image.Decode(resp.Body)
if err != nil {
return nil, err
}
bnds := img.Bounds()
if bnds.Dx() > 1024 {
c.Infof("Resizing image", bnds.Dx())
img = resize.Resize(1024, 0, img, resize.Lanczos3)
}
faces, err := findFaces(c, &img)
// todo: should I pass back by reference?
if err != nil {
return nil, err
}
bnds = img.Bounds()
m := image.NewRGBA(image.Rect(0, 0, bnds.Dx(), bnds.Dy()))
draw.Draw(m, bnds, img, image.Point{0,0}, draw.Src)
brd, err := getBeardCached(c)
if (err != nil) {
return nil, err
}
for _, face := range faces {
brd_resized := resize.Resize(uint(face.Rectangle.Width*2), 0, brd, resize.Lanczos3)
brd_bnds := brd_resized.Bounds()
vert := (face.Landmarks.MouthLeft.Y + face.Landmarks.MouthRight.Y) /2 - float32(brd_bnds.Dy()) * 0.5
rb := image.NewRGBA(image.Rect(0, 0, brd_bnds.Dx(), brd_bnds.Dy()))
rad := float64(face.Attributes.Pose.Roll)*math.Pi/180
graphics.Rotate(rb, brd_resized, &graphics.RotateOptions{rad})
mid := face.Rectangle.Left + face.Rectangle.Width / 2
lt := mid - (float32(brd_bnds.Dx()) / 2)
sr := image.Rect(0,0,brd_bnds.Dx()*4,brd_bnds.Dy()*4)
dp := image.Point{int(float64(lt)), int(float64(vert))}
rt := image.Rectangle{dp, dp.Add(sr.Size())}
draw.Draw(m, rt, rb, sr.Min, draw.Over)
}
img_out := image.Image(m)
buffer := new(bytes.Buffer)
if err := jpeg.Encode(buffer, img_out, nil); err != nil {
return nil, err
}
return buffer, nil
}