图像上传接口自动限制图像大小,缩放
parent
2030042f8f
commit
97962d0145
|
@ -12,7 +12,8 @@ import (
|
|||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"github.com/nfnt/resize"
|
||||
"image/jpeg"
|
||||
)
|
||||
|
||||
type FileController struct {
|
||||
|
@ -30,49 +31,29 @@ func (this *FileController) OnUpload(c *gin.Context) {
|
|||
log.Print(err.Error())
|
||||
return
|
||||
}
|
||||
bytes,err := ioutil.ReadAll(file)
|
||||
if nil != err{
|
||||
log.Print(err.Error())
|
||||
return
|
||||
img, name, err := image.Decode(file)
|
||||
bound := img.Bounds()
|
||||
dx := bound.Dx()
|
||||
dy := bound.Dy()
|
||||
log.Printf("%d %d %s",dx,dy,name)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
}
|
||||
header := make([]byte,512)
|
||||
copy(header,bytes)
|
||||
types := http.DetectContentType(header)
|
||||
log.Print(types)
|
||||
// jpg
|
||||
if strings.Contains(types,"jpeg"){
|
||||
defer file.Close()
|
||||
out, err := os.Create("image/" + uid.String() + ".jpg")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer out.Close()
|
||||
out.Write(bytes)
|
||||
log.Print(len(bytes))
|
||||
c.JSON(200, map[string] interface{}{"url":uid.String() + ".jpg" })
|
||||
// resize to width 1000 using Lanczos resampling
|
||||
// and preserve aspect ratio
|
||||
if(dx > 800){
|
||||
dx = dx / 2;
|
||||
}
|
||||
if strings.Contains(types,"png"){
|
||||
defer file.Close()
|
||||
out, err := os.Create("image/" + uid.String() + ".png")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer out.Close()
|
||||
out.Write(bytes)
|
||||
log.Print(len(bytes))
|
||||
c.JSON(200, map[string] interface{}{"url":uid.String() + ".png" })
|
||||
}
|
||||
if strings.Contains(types,"gif"){
|
||||
defer file.Close()
|
||||
out, err := os.Create("image/" + uid.String() + ".gif")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer out.Close()
|
||||
out.Write(bytes)
|
||||
log.Print(len(bytes))
|
||||
c.JSON(200, map[string] interface{}{"url":uid.String() + ".gif" } )
|
||||
m := resize.Resize(uint(dx), 0, img, resize.Lanczos3)
|
||||
|
||||
datout, err := os.Create("image/" + uid.String() + "." + name)
|
||||
defer datout.Close()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
jpeg.Encode(datout, m, nil)
|
||||
c.JSON(200, map[string] interface{}{"url":uid.String() + "." + name } )
|
||||
|
||||
}
|
||||
|
||||
func (this *FileController) FileList(c *gin.Context) {
|
||||
|
|
Loading…
Reference in New Issue