英文:
Converting multipart file to an image object in golang
问题
我正在尝试上传一张图片,调整其大小,然后将其上传到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:
英文:
I'm attempting to upload an image, resize it and then upload it to Amazon S3 in go, however I'm struggling to figure out how to convert the image from multipart.File to 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})
}
I'm getting the error controllers/resize_controller.go:43: cannot use file (type multipart.File) as type image.Image in argument to resize.Resize:
答案1
得分: 4
我明白了,我只需要使用以下代码:
image, err := jpeg.Decode(file)
英文:
Figured it out, I just needed to use
image, err := jpeg.Decode(file)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论