Fetch the repository succeeded.
package imagedecode
import (
"bytes"
"errors"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io/ioutil"
"os"
)
var GIF = []byte("GIF")
var BMP = []byte("BM")
var JPG = []byte{0xff, 0xd8, 0xff}
var PNG = []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}
const (
GIF_TYPE = "image/gif"
BMP_TYPE = "image/x-ms-bmp"
JPG_TYPE = "image/jpeg"
PNG_TYPE = "image/png"
)
func Decode(imgName string) (image.Image, error) {
i, ee := os.Open(imgName)
defer i.Close()
if ee != nil {
return nil, ee
}
it, e := GetImageType(imgName)
if e != nil {
return nil, e
}
switch it {
case GIF_TYPE:
return gif.Decode(i)
case JPG_TYPE:
return jpeg.Decode(i)
case PNG_TYPE:
return png.Decode(i)
default:
return nil, errors.New("undefined type")
}
}
func GetImageType(imgName string) (string, error) {
fi, e := ioutil.ReadFile(imgName)
if e != nil {
panic(e)
}
var itype string
if bytes.Equal(PNG, fi[0:8]) {
itype = PNG_TYPE
}
if bytes.Equal(GIF, fi[0:3]) {
itype = GIF_TYPE
}
if bytes.Equal(BMP, fi[0:2]) {
itype = BMP_TYPE
}
if bytes.Equal(JPG, fi[0:3]) {
itype = JPG_TYPE
}
if itype == "" {
return itype, errors.New("undefined type")
} else {
return itype, nil
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。