golang实现图片缩放服务器

来源:转载

测试地址

http://127.0.0.1:6789/1000/789.png

http://127.0.0.1:6789/400/789.png

中间数字是图片尺寸

packagemain

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}

版权声明:本文为博主原创文章,未经博主允许不得转载。



分享给朋友:
您可能感兴趣的文章:
随机阅读: