mirror of
https://github.com/woodchen-ink/webp_server_go.git
synced 2025-07-18 13:42:02 +08:00
Fix read file type bug.
This commit is contained in:
parent
8bdffcc246
commit
d8c8bf9964
@ -10,6 +10,7 @@ import (
|
|||||||
"image/png"
|
"image/png"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -32,11 +33,19 @@ var configPath string
|
|||||||
func webpEncoder(p1, p2 string, quality float32) {
|
func webpEncoder(p1, p2 string, quality float32) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
var img image.Image
|
var img image.Image
|
||||||
data, _ := ioutil.ReadFile(p1)
|
|
||||||
if strings.Contains(p1, "jpg") || strings.Contains(p1, "jpeg") {
|
file_data, err := os.Open(p1)
|
||||||
img, _ = jpeg.Decode(bytes.NewReader(data))
|
if err != nil {
|
||||||
} else if strings.Contains(p1, "png") {
|
panic(err)
|
||||||
img, _ = png.Decode(bytes.NewReader(data))
|
}
|
||||||
|
img_data, _ := ioutil.ReadFile(p1)
|
||||||
|
defer file_data.Close()
|
||||||
|
|
||||||
|
contentType, err := GetFileContentType(file_data)
|
||||||
|
if strings.Contains(contentType, "jpg") || strings.Contains(contentType, "jpeg") {
|
||||||
|
img, _ = jpeg.Decode(bytes.NewReader(img_data))
|
||||||
|
} else if strings.Contains(contentType, "png") {
|
||||||
|
img, _ = png.Decode(bytes.NewReader(img_data))
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := webp.Encode(&buf, img, &webp.Options{Lossless: true, Quality: quality}); err != nil {
|
if err := webp.Encode(&buf, img, &webp.Options{Lossless: true, Quality: quality}); err != nil {
|
||||||
@ -188,3 +197,18 @@ func Find(slice []string, val string) (int, bool) {
|
|||||||
}
|
}
|
||||||
return -1, false
|
return -1, false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetFileContentType(out *os.File) (string, error) {
|
||||||
|
|
||||||
|
buffer := make([]byte, 512)
|
||||||
|
|
||||||
|
_, err := out.Read(buffer)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
// content-type by returning "application/octet-stream" if no others seemed to match.
|
||||||
|
contentType := http.DetectContentType(buffer)
|
||||||
|
|
||||||
|
return contentType, nil
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user