ausheng

go实现获取图片文件的扩展名

package common
 
import (
	"fmt"
	"os"
)
 
func GetImgExt(file string) (ext string, err error) {
	var headerByte []byte
	headerByte = make([]byte, 8)
	fd, err := os.Open(file)
	if err != nil {
		return "", err
	}
 
	defer fd.Close()
	_, err = fd.Read(headerByte)
	if err != nil {
		return "", err
	}
	xStr := fmt.Sprintf("%x", headerByte)
	switch {
	case xStr == "89504e470d0a1a0a":
		ext = ".png"
	case xStr == "0000010001002020":
		ext = ".ico"
	case xStr == "0000020001002020":
		ext = ".cur"
	case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
		ext = ".gif"
	case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
		ext = ".tga"
	case xStr[:8] == "464f524d":
		ext = ".iff"
	case xStr[:8] == "52494646":
		ext = ".ani"
	case xStr[:4] == "4d4d" || xStr[:4] == "4949":
		ext = ".tiff"
	case xStr[:4] == "424d":
		ext = ".bmp"
	case xStr[:4] == "ffd8":
		ext = ".jpg"
	case xStr[:2] == "0a":
		ext = ".pcx"
	default:
		ext = ""
	}
	return ext, nil
}

ausheng

爱生活,爱编程

AUSHENG – BLOG

不要害羞,保持联系。我们喜欢结识有趣的人,结交新朋友。