-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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