Last active
April 16, 2025 17:28
-
-
Save sergiotapia/7882944 to your computer and use it in GitHub Desktop.
Golang - Getting the dimensions of an image. jpg, jpeg, png
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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, theimage
package is not suitable for calculating image dimensions, e.g. for putting it on html page with<img width="" height="">
.