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
+7.2k Golang : Convert source code to assembly language
+34.2k Golang : Smarter Error Handling with strings.Contains()
+10.8k Golang : Web routing/multiplex example
+25.4k Golang : How to write CSV data to file
+9.4k Golang : Detect number of active displays and the display's resolution
+20.2k Golang : Secure(TLS) connection between server and client
+7.3k Gogland : Single File versus Go Application Run Configurations
+5.7k Golang : Function as an argument type example
+18.5k Golang : convert int to string
+4.4k Javascript : Access JSON data example
+9.9k Golang : How to get quoted string into another string?
+6.1k Golang : Detect face in uploaded photo like GPlus