Advertisement

根据图片URL获取尺寸

阅读量:

获取图片结构体

复制代码
    package main
    import (
    	"github.com/disintegration/imageorient"
    	_ "golang.org/x/image/webp"
    	"image"
    	_ "image/gif"
    	_ "image/jpeg"
    	_ "image/png"
    	"net/http"
    )
    
    func GetImage(url string) (image.Image, error) {
    	resp, err := http.Get(url)
    	defer resp.Body.Close()
    	if err != nil {
    		return nil, err
    	}
    	img, _, err := imageorient.Decode(resp.Body)
    	if err != nil {
    		return nil, err
    	}
    	return img, nil
    }

注意事项:

  1. 引入解码包
复制代码
    import (
    	_ "image/gif"
    	_ "image/jpeg"
    	_ "image/png"
    )

采用ImageOrient库提供的解码功能而非采用Image库的标准解码方法。其原因在于Image库的解析过程可能会导致部分图片出现自动旋转现象

复制代码
    img, _, err := imageorient.Decode(resp.Body)
  1. 兼容webp格式解析
复制代码
    import (
    _ "golang.org/x/image/webp"
    )

全部评论 (0)

还没有任何评论哟~