[英]how to get image resolution from url in golang
如何从 golang 中的 URL 获取图像的分辨率。
下面是我正在尝试的代码。
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())
你们能告诉我如何在上述情况下获得解决方案
您快到了。 您的g
变量是image.Rectangle
类型,它具有Dx()
和Dy()
方法,分别给出宽度和高度。 我们可以使用这些来计算分辨率。
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
解码整个图像,使用image.DecodeConfig
代替只解析图像头:
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.