英文:
how to get image resolution from url in golang
问题
如何在golang中从URL获取图像的分辨率。
以下是我尝试的代码。
resp, err := http.Get("http://i.imgur.com/Peq1U1u.jpg")
if err != nil {
// 处理错误
}
defer resp.Body.Close()
m, _, err := image.Decode(resp.Body)
if err != nil {
// 处理错误
}
g := m.Bounds()
fmt.Printf(g.String())
你们能告诉我如何在上述情况下获取分辨率吗?
英文:
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
答案1
得分: 13
你离成功就差一点了。你的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()
// 获取高度和宽度
height := g.Dy()
width := g.Dx()
// 分辨率为高度乘以宽度
resolution := height * width
// 打印结果
fmt.Println(resolution, "像素")
}
希望对你有帮助!
英文:
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")
}
答案2
得分: 3
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 // 处理错误
}
defer resp.Body.Close()
img, _, err := image.DecodeConfig(resp.Body)
if err != nil {
return // 处理错误
}
fmt.Println(img.Width * img.Height, "像素")
}
英文:
image.Decode
decodes the entire image, use image.DecodeConfig
instead to parse only the image header:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论