Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

获取图片尺寸大小问题 #122

Open
codcodog opened this issue Sep 2, 2020 · 0 comments
Open

获取图片尺寸大小问题 #122

codcodog opened this issue Sep 2, 2020 · 0 comments
Labels

Comments

@codcodog
Copy link
Owner

codcodog commented Sep 2, 2020

获取图片尺寸大小问题

场景

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 codcodog added the Golang label Sep 2, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant