JPEG Image Resizing with Go & Gin

Rasil Baidar
2 min readJun 22, 2022

--

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:-

  1. Controller
  2. Service
  3. Utils

Controller

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 imageService.Resizefunction.

Service

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.

Utils

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:-

resize.Resize(350,350,img,resize.Lanczos2)

But for this example, let’s stick with hardcoded 250,250 for simplicity.

That's it !!!

Attached below is the demo result:-

Original Image of 168K size with 1140 X 600 resolutions
Resized image to size 12KB with 250 X 250 resolution.

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

Parting Notes:-

For more advanced implementation you can modify the code to take user-specified dimensions for the image to be resized.

Happy coding fellas.

--

--

Rasil Baidar

Web App Developer | Smart Contract Developer | Fitness Enthusiast