Hello fellow coders, if you want to know how we can parse images in Go web API and return a resized image, you have come to the right place. In this blog, I will show you how to parse files in Go and return a base64 string of resized images for your frontend to use.
Prerequisite :- An api route in your go web api service using gin framework.
To have a good understanding of how everything is working, let's divide this article into 3 sections:-
First, we parse the files sent on our server. Let's first set up our controller. From our front end, a multipart form should be sent to our server with attached files on the ‘file’ key.
In this part, we just parsed files sent to our server and pass those files to our services, and return the resized image/s processed by our
Here we loop over all the files sent and then read those files, decode them, and passes the decoded jpeg bytes on
utils.ResizeImg where image bytes are resized. The resized image is then passed to
utils.ConvertToBase64 function to get the base64 string.
Here I used the ‘resize’ package with its provided Lanczos2 algorithm for resizing the image to 250 x 250-pixel size. You can always send values other than 250, 250 through parameter for eg:-
But for this example, let’s stick with hardcoded 250,250 for simplicity.
That's it !!!
Attached below is the demo result:-
Disclaimer :- In this tutorial, it does not save resized image to your machine, it just sends base64 string of resized image, so above resized image example is taken by converting base64 string to jpeg and downloaded it by using this site
For more advanced implementation you can modify the code to take user-specified dimensions for the image to be resized.
Happy coding fellas.