【问题标题】:Converting multipart file to an image object in golang在golang中将多部分文件转换为图像对象
【发布时间】:2015-10-16 19:25:45
【问题描述】:

我正在尝试上传一张图片,调整它的大小,然后在 go 中将其上传到 Amazon S3,但是我正在努力弄清楚如何将图片从 multipart.File 转换为 image.Image

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:

【问题讨论】:

    标签: go amazon-s3


    【解决方案1】:

    想通了,我只需要使用

    image, err := jpeg.Decode(file)

    【讨论】:

    • 请注意,这只会解码 JPG 图像。最好使用自动检测图像格式的image.Decode()。但请记住,您需要导入才能使其工作,例如import _ "image/png"。有关详细信息,请参阅image 的包文档。
    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2016-02-14
    • 2020-07-26
    • 2021-08-04
    • 2022-01-08
    相关资源
    最近更新 更多