Golang : Get dimension(width and height) of image file
If you need to open up an image file, be it jpeg, png or gif. Chances are you will need to know the dimension - width and height of the image before manipulating it.
You will have to use image.DecodeConfig() function to get the color model and dimension data.
Here is an example code in Golang on how to get an image dimension - width and height.
package main
import (
"fmt"
"image"
"image/jpeg"
"os"
)
func init() {
// damn important or else At(), Bounds() functions will
// caused memory pointer error!!
image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig)
}
func main() {
imgfile, err := os.Open("./img.jpg")
if err != nil {
fmt.Println("img.jpg file not found!")
os.Exit(1)
}
defer imgfile.Close()
// get image height and width with image/jpeg
// change accordinly if file is png or gif
imgCfg, _, err := image.DecodeConfig(imgfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
width := imgCfg.Width
height := imgCfg.Height
fmt.Println("Width : ", width)
fmt.Println("Height : ", height)
}
Sample output :
Width : 760
Height : 479
References :
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
+8.8k Golang : Translate language with language package example
+9.7k Golang : Simple image viewer with Go-GTK
+21.2k Golang : Convert Unix timestamp to UTC timestamp
+14.4k Golang : Loop each day of the current month example
+10.3k Golang : GTK Input dialog box examples
+11.7k Golang : http.Get example
+38.8k Golang : How do I convert int to uint8?
+5.4k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+9.2k Golang : How to profile or log time spend on execution?
+12k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+20.8k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+8.9k Golang : Find and replace data in all files recursively