You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/image/image.go

95 lines
1.7 KiB
Go

package image
import (
"bytes"
"image/gif"
"image/jpeg"
"image/png"
"io"
"io/ioutil"
"mime/multipart"
"os"
)
// CompressImage 壓縮圖片至指定位置
func CompressImage(input interface{}, output string) (err error) {
var file io.Reader
switch input.(type) {
case string:
if file, err = os.Open(input.(string)); err != nil {
return err
}
defer func() {
_ = file.(*os.File).Close()
}()
defer os.Remove(input.(string))
case *multipart.FileHeader:
fileHeader := input.(*multipart.FileHeader)
file, err = fileHeader.Open()
if err != nil {
return err
}
defer func() {
_ = file.(multipart.File).Close()
}()
}
bs, err := ioutil.ReadAll(file)
if err != nil {
return err
}
var ext string
if _, err = jpeg.Decode(bytes.NewReader(bs)); err == nil {
ext = "jpg"
} else if _, err = png.Decode(bytes.NewReader(bs)); err == nil {
ext = "png"
} else if _, err = gif.Decode(bytes.NewReader(bs)); err == nil {
ext = "gif"
}
outputFile, err := os.Create(output)
if err != nil {
return err
}
defer outputFile.Close()
switch ext {
case "jpg":
img, err := jpeg.Decode(bytes.NewReader(bs))
if err != nil {
return err
}
if err = jpeg.Encode(outputFile, img, &jpeg.Options{Quality: 70}); err != nil {
return err
}
case "png":
img, err := png.Decode(bytes.NewReader(bs))
if err != nil {
return err
}
encoder := png.Encoder{CompressionLevel: png.BestCompression}
if err = encoder.Encode(outputFile, img); err != nil {
return err
}
case "gif":
img, err := gif.DecodeAll(bytes.NewReader(bs))
if err != nil {
return err
}
if err = gif.EncodeAll(outputFile, img); err != nil {
return err
}
default:
if _, err = outputFile.Write(bs); err != nil {
return err
}
}
return nil
}