Golang : Resize Image
Somehow...just feel like writing a tutorial on how to resize image with Golang today while writing out references for Golang's image package today.
Today's web application will most likely to include profile photo of the users and this usually involve cropping and resizing images uploaded by the users.
In this tutorial, I will use the resize photo functions from this excellent https://github.com/disintegration/imaging package - a fairly simple and compatible with standard Go's image packages.
With much further ado, here's the codes :
package main
import (
"github.com/disintegration/imaging"
"os"
"runtime"
"fmt"
)
func main() {
// maximize CPU usage for maximum performance
runtime.GOMAXPROCS(runtime.NumCPU())
// load original image
img, err := imaging.Open("./big.jpg")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// resize image from 1000 to 500 while preserving the aspect ration
// Supported resize filters: NearestNeighbor, Box, Linear, Hermite, MitchellNetravali,
// CatmullRom, BSpline, Gaussian, Lanczos, Hann, Hamming, Blackman, Bartlett, Welch, Cosine.
dstimg := imaging.Resize(img, 500, 0, imaging.Box)
// save resized image
err = imaging.Save(dstimg, "./resized.jpg")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// everything ok
fmt.Println("Image resized")
}
Here are some of the resized image samples :
Big.jpg(original)
Gaussian
Lanczos
Box
Notes :
In case you have trouble getting the imaging package. See this how to set GOPATH and fix the cannot error tutorial.
References :
See also : Golang : Crop image
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+15.5k Golang : rune literal not terminated error
+15.1k Golang : How to check if IP address is in range
+35.9k Golang : Get file last modified date and time
+17.4k Golang : Get future or past hours, minutes or seconds
+8.8k Golang : Accept any number of function arguments with three dots(...)
+22.5k Generate checksum for a file in Go
+8.3k Golang : Convert word to its plural form example
+7.8k Golang : Ways to recover memory during run time.
+6.1k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+11.3k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+5.7k Get website traffic ranking with Similar Web or Alexa
+15.2k Golang : Get timezone offset from date or timestamp