How to get Dimensions of an image type jpg jpeg png or gif ?


The return type of DecodeConfig config function is struct image which have 2 int variables Width and Height through which you get the dimensions of any jpg jpeg gif or png image in Go.

Example

package main

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

func main() {
	imagePath := "jellyfish.jpg"
	
    file, err := os.Open(imagePath)
	defer file.Close();
    if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
    }
	
    image, _, err := image.DecodeConfig(file) // Image Struct
    if err != nil {
        fmt.Fprintf(os.Stderr, "%s: %v\n", imagePath, err)
    }
	fmt.Println("Width:", image.Width, "Height:", image.Height)    
}

Output

Width: 758 Height: 569
Most Helpful This Week