Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
}
@variadico

This comment has been minimized.

Copy link

commented Aug 3, 2015

I was just passing by and noticed this piece of code.

if err != nil {
    fmt.Fprintf(os.Stderr, "%v\n", err)
}

It can be written this way too.

if err != nil {
    log.Println(err)
}

Before

if err != nil {
    fmt.Fprintf(os.Stderr, "%s: %v\n", imagePath, err)
}

After

if err != nil {
    log.Println(imagePath, err)
}

The log package writes to stderr. Okay, bye. :)

@josephspurrier

This comment has been minimized.

Copy link

commented Aug 30, 2015

Don't forget to close the file:
defer file.Close();

@martinlindhe

This comment has been minimized.

Copy link

commented Dec 29, 2015

If you already have loaded an image with image.Decode(), you can also

b := img.Bounds()
imgWidth := b.Max.X
imgHeight := b.Max.Y
@Deleplace

This comment has been minimized.

Copy link

commented Jan 12, 2017

Thanks! I had never properly noticed the existence of func image.DecodeConfig before, which is great for me because I don't want to decode the whole image just to know its dimensions.

@mkyung

This comment has been minimized.

Copy link

commented Jun 29, 2019

If you already have loaded an image with image.Decode(), you can also

b := img.Bounds()
imgWidth := b.Max.X
imgHeight := b.Max.Y

Great advice! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.