1 Star 0 Fork 0

blackjack/imagedecode

Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
imagedecode.go 1.19 KB
Copy Edit Raw Blame History
qudexin authored 2017-05-11 14:56 +08:00 . new
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
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/vchuzu/imagedecode.git
git@gitee.com:vchuzu/imagedecode.git
vchuzu
imagedecode
imagedecode
09672b44b2fa

Search