将多部分文件转换为Golang中的图像对象

huangapple go评论88阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2015年10月16日 19:06:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/33168973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定