From 97962d0145a2ad0dd2cb184acfd4cd593dc3b3ab Mon Sep 17 00:00:00 2001 From: "DESKTOP-4RNDQIC\\29019" <290198252@qq.com> Date: Tue, 26 Jan 2021 23:45:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=BE=E5=83=8F=E4=B8=8A=E4=BC=A0=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E8=87=AA=E5=8A=A8=E9=99=90=E5=88=B6=E5=9B=BE=E5=83=8F?= =?UTF-8?q?=E5=A4=A7=E5=B0=8F=EF=BC=8C=E7=BC=A9=E6=94=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/file.go | 63 ++++++++++++++++------------------------------ 1 file changed, 22 insertions(+), 41 deletions(-) diff --git a/controller/file.go b/controller/file.go index a64c32f..a8d5732 100644 --- a/controller/file.go +++ b/controller/file.go @@ -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) {