2015-10-16 149 views
0

我试图上传图像,调整大小,然后将其上传到Amazon S3中,但是我正在努力弄清楚如何将图像从multipart.File到image.Image将multipart文件转换为golang中的图像对象

package controllers 

import (
    "github.com/gin-gonic/gin" 
    "github.com/mitchellh/goamz/aws" 
    "github.com/mitchellh/goamz/s3" 
    "github.com/nfnt/resize" 
    _ "image/jpeg" 
    "log" 
    "os" 
    "strconv" 
) 

type ResizeController struct { 
} 

func NewResizeController() *ResizeController { 
    return &ResizeController{} 
} 

func (rc ResizeController) Resize(c *gin.Context) { 

    auth, err := aws.EnvAuth() 

    if err != nil { 
     log.Fatal(err) 
    } 

    client := s3.New(auth, aws.EUWest) 
    bucket := client.Bucket(os.Getenv("AWS_BUCKET_NAME")) 

    file, header, err := c.Request.FormFile("file") 
    filename := header.Filename 

    height := c.Query("height") 
    width := c.Query("width") 

    h64, err := strconv.ParseUint(height, 10, 32) 
    w64, err := strconv.ParseUint(width, 10, 32) 
    h := uint(h64) 
    w := uint(w64) 

    m := resize.Resize(w, h, file, resize.Lanczos3) 

    err = bucket.Put("/content/"+filename, m, "content-type", s3.Private) 

    c.JSON(200, gin.H{"filename": header.Filename}) 
} 

,我发现了错误controllers/resize_controller.go:43: cannot use file (type multipart.File) as type image.Image in argument to resize.Resize:

回答

0

想通了,我只需要使用

image, err := jpeg.Decode(file)

+7

注意是t他只会解码JPG图像。使用自动检测图像格式的['image.Decode()'](https://golang.org/pkg/image/#Decode)会更好。但请记住,您需要导入才能正常工作,例如'import _“image/png”'。有关详细信息,请参阅['image']的包doc(https://golang.org/pkg/image/)。 – icza

+0

大喊,@icza –