Skip to content

Instantly share code, notes, and snippets.

@sergiotapia
Last active April 16, 2025 17:28
Show Gist options
  • Save sergiotapia/7882944 to your computer and use it in GitHub Desktop.
Save sergiotapia/7882944 to your computer and use it in GitHub Desktop.
Golang - Getting the dimensions of an image. jpg, jpeg, png
package main
import (
"fmt"
"image"
"os"
_ "image/jpeg"
_ "image/png"
)
func main() {
width, height := getImageDimension("rainy.jpg")
fmt.Println("Width:", width, "Height:", height)
}
func getImageDimension(imagePath string) (int, int) {
file, err := os.Open(imagePath)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
image, _, err := image.DecodeConfig(file)
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", imagePath, err)
}
return image.Width, image.Height
}
@movsb
Copy link

movsb commented Apr 16, 2025

If you use exiftool to inspect some images, they may have a property named Orientation/Rotation, which tells you how to rotate that image before displaying. A 4(width)x3(height) image may be displayed as a portrait. After having noticed this, the image package is not suitable for calculating image dimensions, e.g. for putting it on html page with <img width="" height="">.

$ exiftool -json -ImageSize -Orientation IMG_0695.JPG
[{
  "SourceFile": "IMG_0695.JPG",
  "ImageSize": "4032x3024",
  "Orientation": "Rotate 90 CW"
}]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment