3 回答
TA贡献1817条经验 获得超14个赞
通常所做的是检查文件是否具有您想要的图像文件格式的正确幻数。虽然这个测试不是非常准确,但通常已经足够了。你可以使用这样的代码:
package foo
import "strings"
// image formats and magic numbers
var magicTable = map[string]string{
"\xff\xd8\xff": "image/jpeg",
"\x89PNG\r\n\x1a\n": "image/png",
"GIF87a": "image/gif",
"GIF89a": "image/gif",
}
// mimeFromIncipit returns the mime type of an image file from its first few
// bytes or the empty string if the file does not look like a known file type
func mimeFromIncipit(incipit []byte) string {
incipitStr := []byte(incipit)
for magic, mime := range magicTable {
if strings.HasPrefix(incipitStr, magic) {
return mime
}
}
return ""
}
- 3 回答
- 0 关注
- 222 浏览
添加回答
举报