2017-04-25 20:05:59 +08:00
|
|
|
package graphics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"image"
|
2017-05-13 14:43:03 +08:00
|
|
|
"image/gif"
|
|
|
|
"image/jpeg"
|
|
|
|
"image/png"
|
2017-04-25 20:05:59 +08:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
)
|
2017-05-13 14:43:03 +08:00
|
|
|
|
2017-04-25 20:05:59 +08:00
|
|
|
// 将图片保存到指定的路径
|
|
|
|
func SaveImage(p string, src image.Image) error {
|
|
|
|
|
2018-01-26 17:17:38 +08:00
|
|
|
os.MkdirAll(filepath.Dir(p), 0666)
|
2017-06-05 13:55:07 +08:00
|
|
|
|
2017-05-13 14:43:03 +08:00
|
|
|
f, err := os.OpenFile(p, os.O_SYNC|os.O_RDWR|os.O_CREATE, 0666)
|
2017-04-25 20:05:59 +08:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
ext := filepath.Ext(p)
|
|
|
|
|
|
|
|
if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") {
|
|
|
|
|
2017-05-13 14:43:03 +08:00
|
|
|
err = jpeg.Encode(f, src, &jpeg.Options{Quality: 80})
|
|
|
|
|
2017-04-25 20:05:59 +08:00
|
|
|
} else if strings.EqualFold(ext, ".png") {
|
|
|
|
err = png.Encode(f, src)
|
|
|
|
} else if strings.EqualFold(ext, ".gif") {
|
2017-05-13 14:43:03 +08:00
|
|
|
err = gif.Encode(f, src, &gif.Options{NumColors: 256})
|
2017-04-25 20:05:59 +08:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|