Blog icon indicating copy to clipboard operation
Blog copied to clipboard

获取图片尺寸大小问题

Open codcodog opened this issue 4 years ago • 0 comments

获取图片尺寸大小问题

场景

Golang 使用 Gin 框架,获取上传图片大小的时候,报 image: unknown format

方案

摘录部分代码如下

func uploadOpcategoryImage(c *bm.Context) {
    ...

	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(nil, ecode.Error(ecode.RequestErr, err.Error()))
		return
	}
	defer file.Close()

	// 校验尺寸大小
	image, _, err := image.DecodeConfig(file)
	if err != nil {
		c.JSON(nil, ecode.Error(ecode.RequestErr, err.Error()))
		return
	}
	if image.Width != 128 || image.Height != 128 {
		c.JSON(nil, ecode.Error(ecode.RequestErr, "图片尺寸只支持128px*128px"))
		return
	}

    ...
}

image.DecodeConfig() 函数会报 image: unknown format.

这是因为没有导入对应图片格式的包导致的,image 包本身不能识别图片格式.

在文件开头导入相应的图片格式包即可

import (
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
)

另外需要注意的是 c.Request.FormFile("file") 返回的是文件指针,image.DecodeConfig(file) 之后,file 的内容是被修改的了.

codcodog avatar Sep 02 '20 02:09 codcodog