duanba8173 2015-06-17 15:34
浏览 207
已采纳

当源为多部分时,image.Decode导致“未知格式”。File

I have a multipart.File that a user uploads to my server, and then I take that file and upload it to s3 using aws-sdk-go, but I also want to create a thumbnail of that image.

The code below works fine in my tests when I file is the return value of an os.Open(... of a local file, but it hit's the err block when I send CreateThumbnail the same variable I sent to s3, which asks for an io.Reader

import (
  "image"
  "image/jpeg"
)
func UploadToS3(file multipart.File, /*snip*/) {
  _, uploadErr := uploader.Upload(&s3manager.UploadInput{
    Bucket: aws.String(bucket),
    Key:    aws.String(key),
    Body:   file,
    ContentType: aws.String(mimeType),
    ACL: aws.String("public-read"),
  })
  reader, err := CreateThumbnail(file)
}    

func CreateThumbnail(imageFile io.Reader) (io.Reader, error) {
  decodedImage, _, err := image.Decode(imageFile)
  if err != nil {
   fmt.Println("Error decoding", err, decodedImage) // "unknown format"
   return nil, err
 }
 /*snip*/

Most of the answers I see for the problem involve adding import _ "image/jpeg", but that's already imported (as well as png and gif). I'm fairly new to Golang, so I'm a bit lost as to what I'm doing wrong. I tried image.Decode(bufio.NewReader(imageFile)) as well, but that results in the same err.

  • 写回答

1条回答 默认 最新

  • duanpuluan0480 2015-06-18 05:40
    关注

    The call uploader.Upload reads to the end of the file. Seek back to the beginning of the file before calling CreateThumbnail:

    func UploadToS3(file multipart.File, /*snip*/) {
      _, uploadErr := uploader.Upload(&s3manager.UploadInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
        Body:   file,
        ContentType: aws.String(mimeType),
        ACL: aws.String("public-read"),
      })
      // Seek back to beginning of file for CreateThumbnail
      if _, err := file.Seek(0, 0); err != nil {
        // handle error
      }
      reader, err := CreateThumbnail(file)
    }    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于 S7-PLCSIM Advanced 5.0本地TCP连接无法读写数据
  • ¥15 关于温度改变石墨烯介电性能(关键词-介电常数)
  • ¥150 HDMI分路器LT86102 的输出在890MHz频点处EMC超标8DB
  • ¥15 druid(相关搜索:数据库|防火墙)
  • ¥15 大一python作业
  • ¥15 preLaunchTask"C/C++: aarch64- apple-darwin22-g++-14 生成活动 文件”已终止,退出代码为-1。
  • ¥60 如何鉴定微信小程序数据被篡改过
  • ¥18 关于#贝叶斯概率#的问题:这篇文章中利用em算法求出了对数似然值作为概率表参数,然后进行概率表计算,这个概率表是怎样计算的呀
  • ¥20 C#上传XML格式数据
  • ¥15 elementui上传结合oss接口断点续传,现在只差停止上传和继续上传,各大精英看下