Home
Map
Image Width, Height From FileUse the image package to get the width and height of an image file, calling the DecodeConfig method.
Golang
This page was last reviewed on Dec 20, 2022.
Image. Suppose you have an image file (a PNG or JPG) and wish to get its width and height in a Golang program. This can be done with the "image" package.
Some details. With images, we can get the Width and Height from the image file just by parsing the file. We simply call DecodeConfig on a JPG or PNG.
An example. To begin, we must import the "image" module. If we import the "image/jpeg" and "image/png" modules as well, we get full support for those types.
Detail We call os.Open on the image file, and then bufio.NewReader to get a Reader for the file.
Detail This function receives the Reader we just created by calling bufio.Reader. It returns a Config instance.
Detail This will contain some useful details about the image, like Width and Height. The image format is also available.
package main import ( "fmt" "os" "bufio" "image" _ "image/jpeg" _ "image/png" ) func main() { path := `C:\programs\zip-chart.png` // Open file. inputFile, _ := os.Open(path) reader := bufio.NewReader(inputFile) // Decode image. config, _, _ := image.DecodeConfig(reader) // Print config. fmt.Printf("IMAGE: width=%v height=%v\n", config.Width, config.Height) }
IMAGE: width=300 height=151
Note, imports. If you try to open a JPEG or PNG file without the special import statement for that type, it will not work correctly.
Tip If your program only uses JPEGs, you could remove the PNG import. This probably is not worth doing.
_ "image/jpeg" _ "image/png"
A summary. Image parsing can be done with built-in libraries like the "image" module in Go. It is rarely worth implementing yourself, unless you are trying to learn about image formats.
File
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.