P
P
padrition2020-12-26 15:35:49
go
padrition, 2020-12-26 15:35:49

How to respond to a POST call by sending a JSON image to the frontend in Golang?

Problem: My code is loading an image from the user. It resizes the image and encodes it in my local . I want to send a resized image back to the user and display it in his html file.

main.go file:

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>


directory :
.
    └── go-resize-rest-api
        ├── main.go
        └── resources
            └── html
                └── index.html

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
liquiddeath13, 2020-12-26
@liquiddeath13

If the question implies that you need to display an image in a file with HTML markup, then it is enough to embed it using a tag with image encoding in BASE64

<img src="data:image/расширение;base64, контентМедиаФайла" alt="подпись" />

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question