简体   繁体   English

如何在谷歌云存储中上传调整大小的图像?

[英]How to upload a resized image in Google cloud Storage?

How to upload an image file in Google Cloud Storage that I already resized using 3rd party package "github.com/disintegration/imaging" ?如何在我已经使用第 3 方 package "github.com/disintegration/imaging"调整大小的 Google Cloud Storage 中上传图像文件?

I tried this我试过这个

Code:代码:

f, uploadedFile, err := c.Request.FormFile("file") // image file
    // Decode the file into a image struct
     srcImg, _, err:=  image.Decode(f)

    // Resize srcImage to width = 800px preserving the aspect ratio.
    adjustedFile := imaging.Resize(srcImg, 800, 0, imaging.Lanczos)

    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{
            "message": err.Error(),
            "error":   true,
        })
        return
    }

    defer f.Close()

    sw := storageClient.Bucket(bucket).Object(""+ callType +"/"+ yearString +"/"+ monthString +"/" + uploadedFile.Filename).NewWriter(ctx)
    
    if _, err := io.Copy(sw, adjustedFile); err != nil { // error here
        c.JSON(http.StatusInternalServerError, gin.H{
            "message": err.Error(),
            "error":   true,
        })
        return
    }

Error:错误:

`cannot use adjustedFile (type *image.NRGBA) as type io.Reader in a`rgument to io.Copy:
    *image.NRGBA does not implement io.Reader (missing Read method)

Posting this as a community wiki, since It's based on @CeriseLimon's comment.将此作为社区 wiki 发布,因为它基于 @CeriseLimon 的评论。

The problem is that you have to encode your image to bytes before sending it to GCS and you can do it by using the image/jpeg package, try the following code问题是您必须在将图像发送到 GCS 之前将其编码为字节,您可以使用图像/jpeg package 来完成,尝试以下代码

if _, err := jpeg.Encode(sw, adjustedFile, &jpeg.Options{Quality:77}); err != nil {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM