检查png图像在戈朗中是否全部透明

我有多个像这样的网址,总是返回PNG图像。


https://hydro.nationalmap.gov/arcgis/rest/services/wbd/MapServer/export?bbox=-106.6462299999999885,25.83722399999999908,-93.50780600000010168,36.50038700000000347&size=640,519&bboxSR=4326&layers=show:4&f=image&transparent=true


我想检查从URL返回的图像是否像上面的URL一样都是空的(透明的),或者它里面有一些实际的图像。我通过以下函数发出请求,并检查HTTP状态是否为200,返回的内容类型是否为图像。我需要在此处添加功能以测试图像是否为空。


thumbnail := "https://hydro.nationalmap.gov/arcgis/rest/services/wbd/MapServer/export?bbox=-106.6462299999999885,25.83722399999999908,-93.50780600000010168,36.50038700000000347&size=640,519&bboxSR=4326&layers=show:4&f=image&transparent=true"


resp, err := client.Get(thumbnail)

if err != nil {

    fmt.Println(err)

} else if resp.StatusCode == 200 && strings.HasPrefix(resp.Header["Content-Type"][0], "image") {

    return thumbnail

} else {

    fmt.Println(thumbnail, resp.StatusCode, resp.Header["Content-Type"][0])

}


翻阅古今
浏览 94回答 1
1回答

Smart猫小萌

标准库提供了功能强大的软件包和解码器,使我们能够非常轻松地做到这一点。imageimage/png我们知道透明度意味着 alpha=0,我们需要做的就是迭代图像的像素。package mainimport (&nbsp; &nbsp; "image/png"&nbsp; &nbsp; "io"&nbsp; &nbsp; "log"&nbsp; &nbsp; "net/http")func main() {&nbsp; &nbsp; transparentResp, _ := http.Get("https://upload.wikimedia.org/wikipedia/commons/3/3d/1_120_transparent.png")&nbsp; &nbsp; defer transparentResp.Body.Close()&nbsp; &nbsp; notTransparentResp, _ := http.Get("https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Pitch.png/640px-Pitch.png")&nbsp; &nbsp; defer notTransparentResp.Body.Close()&nbsp; &nbsp; println(isFullyTransparentPng(transparentResp.Body))&nbsp; &nbsp; println(isFullyTransparentPng(notTransparentResp.Body))}func isFullyTransparentPng(reader io.Reader) bool {&nbsp; &nbsp; img, _ := png.Decode(reader)&nbsp; &nbsp; for x := img.Bounds().Min.X; x < img.Bounds().Dx(); x++ {&nbsp; &nbsp; &nbsp; &nbsp; for y := img.Bounds().Min.Y; y < img.Bounds().Dy(); y++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _, _, _, alpha := img.At(x, y).RGBA()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if alpha != 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return true}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go