Skip to content

Instantly share code, notes, and snippets.

@tonythere
Forked from gobijan/gist:1568fb2b35c517f36369
Last active September 9, 2015 03:30
Show Gist options
  • Save tonythere/43003e650edcafeae180 to your computer and use it in GitHub Desktop.
Save tonythere/43003e650edcafeae180 to your computer and use it in GitHub Desktop.
Golang HTTP Handler to Upload Image => Resize => Convert to JPEG => Save to Disk.
func UploadHandler(w http.ResponseWriter, r *http.Request) {
file, _, err := r.FormFile("file")
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
img, _, err := image.Decode(file)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusUnsupportedMediaType), http.StatusUnsupportedMediaType)
return
}
m := resize.Resize(1000, 0, img, resize.Lanczos3)
out, err := os.Create("test_resized.jpg")
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer out.Close()
// Encode into jpeg http://blog.golang.org/go-image-package
err = jpeg.Encode(out, m, nil)
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment