@@ -2,11 +2,15 @@ package main
22
33import (
44 "fmt"
5+ "github.com/chai2010/webp"
56 "github.com/gorilla/mux"
6- "image/png "
7+ "io "
78 "net/http"
9+ "os"
10+ "path"
811 "strconv"
912 "strings"
13+ "time"
1014)
1115
1216// Init the HTTP (or rest api) server
@@ -52,6 +56,14 @@ func handleAvatar(w http.ResponseWriter, r *http.Request) {
5256 }
5357 }
5458
59+ // To prevent overload on the server, we enforce some limits on scaling.
60+ // Not smaller than 16, so that it's visible, and not more than 1024px
61+ if scale < 16 {
62+ scale = 16
63+ } else if scale > 1024 {
64+ scale = 1024
65+ }
66+
5567 var uuid string
5668 var err error
5769
@@ -72,6 +84,18 @@ func handleAvatar(w http.ResponseWriter, r *http.Request) {
7284 }
7385 }
7486
87+ cachePath := path .Join (renderDir , fmt .Sprintf ("%s_%s_%s.web" , mode , uuid , strconv .Itoa (scale )))
88+ cachedFile , err := os .Open (cachePath )
89+ if err == nil {
90+ w .Header ().Set ("Content-Type" , "image/webp" )
91+ _ , err = io .Copy (w , cachedFile )
92+ if err != nil {
93+ http .Error (w , "Failed to read image: " + err .Error (), http .StatusInternalServerError )
94+ }
95+ return
96+ }
97+ defer cachedFile .Close ()
98+
7599 // Request the skin from the MOJANG servers
76100 skinPath , err := fetchSkin (uuid )
77101 if err != nil {
@@ -86,10 +110,18 @@ func handleAvatar(w http.ResponseWriter, r *http.Request) {
86110 }
87111
88112 // Encode the image ready for browser rendering
89- w .Header ().Set ("Content-Type" , "image/png" )
90- err = png .Encode (w , img )
113+ f , _ := os .Create (cachePath )
114+ err = webp .Encode (f , img , & webp.Options {
115+ Lossless : true ,
116+ Quality : 100 ,
117+ Exact : true ,
118+ })
119+
91120 if err != nil {
92- http .Error (w , "Failed to encode image" , http .StatusInternalServerError )
121+ http .Error (w , "Failed to encode image: " + err . Error () , http .StatusInternalServerError )
93122 return
94123 }
124+
125+ w .Header ().Set ("Content-Type" , "image/webp" )
126+ http .ServeContent (w , r , cachePath , time .Now (), f )
95127}
0 commit comments