Проблема: мой код загружает изображение от пользователя. Он изменяет размер изображения и кодирует его в моем локальном директории . Я хочу отправить изображение с измененным размером обратно пользователю и отобразить его в его html-файле.
Main.go файл:
package main
import (
"errors"
"fmt"
"image"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"mime/multipart"
"net/http"
"os"
"github.com/nfnt/resize"
)
func index(rw http.ResponseWriter, r *http.Request) {
http.ServeFile(rw, r, "resources/html/index.html")
}
func autoResize(rw http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 * 1024 * 1024)
imageFile, header, err := r.FormFile("imageFile")
if err != nil {
fmt.Println(err)
return
}
defer imageFile.Close()
imageType := header.Header.Get("Content-Type")
if imageType != "image/png" && imageType != "image/jpeg" && imageType != "image/gif" {
fmt.Println(errors.New("\nEror.A file should be either png, jpeg or gif"))
http.Error(rw, "Inavalid file format", http.StatusBadRequest)
return
}
fileName := header.Filename
resizeAnImage(imageFile, 1000, imageType, fileName)
}
func upload(rw http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 * 1024 * 1024)
imageFile, header, err := r.FormFile("imageFile")
if err != nil {
fmt.Println(err)
return
}
defer imageFile.Close()
imageType := header.Header.Get("Content-Type")
if imageType != "image/png" && imageType != "image/jpeg" && imageType != "image/gif" {
fmt.Println(errors.New("\nEror.A file should be either png, jpeg or gif"))
http.Error(rw, "Inavalid file format", http.StatusBadRequest)
return
}
out, err := os.Create("resources/images/" + header.Filename)
if err != nil {
fmt.Println(err)
}
switch imageType {
case "image/png":
img, err := png.Decode(imageFile)
if err != nil {
fmt.Println(err)
}
png.Encode(out, img)
break
case "image/jpeg":
img, err := jpeg.Decode(imageFile)
if err != nil {
fmt.Println(err)
}
jpeg.Encode(out, img, nil)
break
case "image/gif":
img, err := gif.DecodeAll(imageFile)
if err != nil {
fmt.Println(err)
}
gif.EncodeAll(out, img)
}
}
func resizeAnImage(imageFile multipart.File, width uint, imageType string, fileName string) {
out, err := os.Create("resources/images/" + fileName)
if err != nil {
fmt.Println(err)
}
switch imageType {
case "image/jpeg":
img, err := jpeg.Decode(imageFile)
if err != nil {
fmt.Println(err)
}
jpegImg := resize.Resize(width, 0, img, resize.Lanczos2)
jpeg.Encode(out, jpegImg, nil)
break
case "image/png":
img, err := png.Decode(imageFile)
if err != nil {
fmt.Println(err)
}
pngImg := resize.Resize(width, 0, img, resize.Lanczos2)
png.Encode(out, pngImg)
break
case "image/gif":
newGifImg := gif.GIF{}
gifImg, err := gif.DecodeAll(imageFile)
if err != nil {
fmt.Println(err)
}
for _, img := range gifImg.Image {
resizedGifImg := resize.Resize(width, 0, img, resize.Lanczos2)
palettedImg := image.NewPaletted(resizedGifImg.Bounds(), img.Palette)
draw.FloydSteinberg.Draw(palettedImg, resizedGifImg.Bounds(), resizedGifImg, image.ZP)
newGifImg.Image = append(newGifImg.Image, palettedImg)
newGifImg.Delay = append(newGifImg.Delay, 25)
}
gif.EncodeAll(out, &newGifImg)
break
}
}
func setupRouts() {
http.HandleFunc("/", index)
http.HandleFunc("/upload", upload)
http.HandleFunc("/resize", autoResize)
http.ListenAndServe(":8080", nil)
}
func main() {
setupRouts()
}
index.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Upload an image you want to resize</h1>
<form
enctype="multipart/form-data"
action="http://localhost:8080/upload"
method="post">
<input type="file" name="imageFile" />
<input type="submit" value="upload" />
</form>
<form
enctype="multipart/form-data"
action="http://localhost:8080/resize"
method="post">
<input type="file" name="imageFile" />
<input type="submit" value="resize" />
</form>
</body>
</html>
директория :
.
└── go-resize-rest-api
├── main.go
└── resources
└── html
└── index.html