How to get the resolution of an image from a URL in golang.
Below is the code i am trying.
resp, err := http.Get("http://i.imgur.com/Peq1U1u.jpg")
if err != nil {
// handle error
}
defer resp.Body.Close()
m, _, err := image.Decode(resp.Body)
if err != nil {
// handle error
}
g := m.Bounds()
fmt.Printf(g.String())
Can you guys tell me how to get the resolution in above situation
You're almost there. Your g
variable is of the image.Rectangle
type, which has the Dx()
and Dy()
methods, which give width and height respectively. We can use these to compute the resolution.
package main
import (
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"log"
"net/http"
)
func main() {
resp, err := http.Get("http://i.imgur.com/Peq1U1u.jpg")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
m, _, err := image.Decode(resp.Body)
if err != nil {
log.Fatal(err)
}
g := m.Bounds()
// Get height and width
height := g.Dy()
width := g.Dx()
// The resolution is height x width
resolution := height * width
// Print results
fmt.Println(resolution, "pixels")
}
image.Decode
decodes the entire image, use image.DecodeConfig
instead:
package main
import (
"image"
_ "image/jpeg"
"net/http"
)
func main() {
resp, err := http.Get("http://i.imgur.com/Peq1U1u.jpg")
if err != nil {
return // handle error somehow
}
defer resp.Body.Close()
img, _, err := image.DecodeConfig(resp.Body)
if err != nil {
return // handle error somehow
}
fmt.Println(img.Width * img.Height, "pixels")
}