Sep 252019

ADM

How to get the dimensions of an image in Golang

  • September 25 2019
  • ADM

 

 

How to get the dimensions of an image in Golang - golang

 

In Golang there are two simple methods to get an image dimensions.

Example 1 - Using image.DecodeConfig method

package main

import (
	"fmt"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"os"
)

func main() {

	imgPath := "C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg"

	fmt.Println("How to get image dimmensions - image.DecodeConfig")
	fmt.Println()
	fmt.Println(imgPath)
	file, err := os.Open(imgPath)
	defer file.Close()
	if err != nil {
		fmt.Println(err)
	}

	image, _, err := image.DecodeConfig(file)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Width:", image.Width, "Height:", image.Height)
}

Output

How to get image dimmensions - image.DecodeConfig

C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg
Width: 1024 Height: 768

Example 2 - Using image.Decode method

If the image is already loaded then the dimensions are already available through Bounds method.

package main

import (
	"fmt"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"os"
)

func main() {

	imgPath := "C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg"

	fmt.Println("How to get image dimmensions - image.Decode")
	fmt.Println()
	fmt.Println(imgPath)
	file, err := os.Open(imgPath)
	defer file.Close()
	if err != nil {
		fmt.Println(err)
	}

	image, _, err := image.Decode(file)
	if err != nil {
		fmt.Println(err)
	}
	bounds := image.Bounds()
	fmt.Println("Width:", bounds.Max.X, "Height:", bounds.Max.Y)
}

Output

How to get image dimmensions - image.Decode

C:\Users\Public\Pictures\Sample Pictures\Lighthouse.jpg
Width: 1024 Height: 768

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build imgDim.go

Then depending on if you are on Linux or Windows the binary file is created.

To run the application execute the command.

Linux

$ ./imgDim

Windows

c:\Users\adm\go\tutorials> imgDim.exe

If you want to compile and run the application in one single step run the following command:

go run imgDim.go

References