图像上传接口自动限制图像大小,缩放

master
DESKTOP-4RNDQIC\29019 2021-01-26 23:45:12 +08:00
parent 2030042f8f
commit 97962d0145
1 changed files with 22 additions and 41 deletions

View File

@ -12,7 +12,8 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"strings" "github.com/nfnt/resize"
"image/jpeg"
) )
type FileController struct { type FileController struct {
@ -30,49 +31,29 @@ func (this *FileController) OnUpload(c *gin.Context) {
log.Print(err.Error()) log.Print(err.Error())
return return
} }
bytes,err := ioutil.ReadAll(file) img, name, err := image.Decode(file)
if nil != err{ bound := img.Bounds()
log.Print(err.Error()) dx := bound.Dx()
return dy := bound.Dy()
log.Printf("%d %d %s",dx,dy,name)
if err != nil {
log.Print(err)
} }
header := make([]byte,512) // resize to width 1000 using Lanczos resampling
copy(header,bytes) // and preserve aspect ratio
types := http.DetectContentType(header) if(dx > 800){
log.Print(types) dx = dx / 2;
// 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" })
} }
if strings.Contains(types,"png"){ m := resize.Resize(uint(dx), 0, img, resize.Lanczos3)
defer file.Close()
out, err := os.Create("image/" + uid.String() + ".png") datout, err := os.Create("image/" + uid.String() + "." + name)
if err != nil { defer datout.Close()
log.Fatal(err) 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" } )
} }
jpeg.Encode(datout, m, nil)
c.JSON(200, map[string] interface{}{"url":uid.String() + "." + name } )
} }
func (this *FileController) FileList(c *gin.Context) { func (this *FileController) FileList(c *gin.Context) {