测试地址
中间数字是图片尺寸
package main
import (
"fmt"
"graphics"
"image"
"image/png"
"log"
"net/http"
"os"
"strconv"
"strings"
)
func main() {
http.HandleFunc("/", doImageHandler)
http.ListenAndServe("127.0.0.1:6789", nil)
}func doImageHandler(w http.ResponseWriter, r *http.Request) {fmt.Printf("%q\n", strings.Split(r.URL.Path, "/"))url := strings.Split(r.URL.Path, "/")if len(url) != 3 {return}newdx, uerr := strconv.Atoi(url[1])if uerr != nil {log.Fatal(uerr)}src, err := LoadImage(url[2])bound := src.Bounds()dx := bound.Dx()dy := bound.Dy()if err != nil {log.Fatal(err)}// 缩略图的大小dst := image.NewRGBA(image.Rect(0, 0, newdx, newdx*dy/dx))// 产生缩略图,等比例缩放err = graphics.Scale(dst, src)if err != nil {log.Fatal(err)}header := w.Header()header.Add("Content-Type", "image/jpeg")png.Encode(w, dst)}
// Load Image decodes an image from a file of image.
func LoadImage(path string) (img image.Image, err error) {
file, err := os.Open(path)
if err != nil {
return
}
defer file.Close()
img, _, err = image.Decode(file)
return
}