How to get the dimensions of an image in Golang

  • 20 June 2019
  • ADM

 

How to get the dimensions of an image in Golang - images/logos/golang.jpg

 

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

 

References