github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/utils/img.go (about) 1 package utils 2 3 import ( 4 "bytes" 5 "errors" 6 7 "github.com/fumiama/imgsz" 8 ) 9 10 var ( 11 ErrImageDataTooShort = errors.New("image data is too short") 12 ) 13 14 type ImageFormat uint32 15 16 const ( 17 Unknown ImageFormat = 0000 18 Jpeg ImageFormat = 1000 19 Png ImageFormat = 1001 20 Gif ImageFormat = 2000 21 Webp ImageFormat = 1002 22 Bmp ImageFormat = 1005 23 Tiff ImageFormat = 1006 24 ) 25 26 var formatmap = map[string]ImageFormat{ 27 "jpeg": Jpeg, 28 "png": Png, 29 "gif": Gif, 30 "webp": Webp, 31 "bmp": Bmp, 32 "tiff": Tiff, 33 } 34 35 func (format ImageFormat) String() string { 36 switch format { 37 case Jpeg: 38 return "jpg" 39 case Png: 40 return "png" 41 case Gif: 42 return "gif" 43 case Webp: 44 return "webp" 45 case Bmp: 46 return "bmp" 47 case Tiff: 48 return "tiff" 49 default: 50 return "unknown" 51 } 52 } 53 54 func ImageResolve(image []byte) (format ImageFormat, size imgsz.Size, err error) { 55 if len(image) < 10 { // 最小长度检查 56 err = ErrImageDataTooShort 57 return 58 } 59 60 sz, fmts, err := imgsz.DecodeSize(bytes.NewReader(image)) 61 if err != nil { 62 return 63 } 64 65 return formatmap[fmts], sz, nil 66 }