Golang io.Reader在jpeg.Decode返回EOF的问题

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

Golang io.Reader issue with jpeg.Decode returning EOF

问题

我正在尝试将一个作为 io.Reader 的 multipart.File 解码为 jpeg,并使用 github.com/disintegration/imaging 库将其转换为缩略图。我事先知道数据将是 jpeg 格式的。当我将 multipart.File 发送到 ConvertImageToThumbnail 函数时,它每次都返回 "Unexpected EOF"。我做错了什么?

package images

import (
	"github.com/disintegration/imaging"
	"image"
	"image/jpeg"
	"mime/multipart"
)

func ConvertImageToThumbnail(pic multipart.File) (image.Image, error) {
    pic.Seek(0,0) // 解决方法是将文件指针重新定位到文件开头
	img,err := jpeg.Decode(pic)
	if err != nil {
		return nil, err
	}
	thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom)

	return thumb, nil
}


pic, header, err := r.FormFile("avatar") 
// 检查错误
defer pic.Close()

你的代码看起来基本上是正确的。问题可能是在读取文件之前,文件指针的位置不正确。通过在调用 pic.Seek(0,0) 将文件指针重新定位到文件开头,你可以解决这个问题。这样,jpeg.Decode(pic) 将从文件的开头开始读取数据,而不是从当前位置开始读取,从而避免了 "Unexpected EOF" 错误。

英文:

I am trying to take a multipart.File that is an io.Reader and decode it as a jpeg to covert into a Thumbnail using github.com/disintegration/imaging's library. I know in advance the data is going to be a jpeg. When I send the multipart.File to a ConvertImageToThumbnail function and it returns Unexpected EOF every time. What am I doing wrong?

package images

import (
	"github.com/disintegration/imaging"
	"image"
	"image/jpeg"
	"mime/multipart"
)

func ConvertImageToThumbnail(pic multipart.File) (image.Image, error) {
    pic.Seek(0,0) // The solution was to seek back to the beginning of the file
	img,err := jpeg.Decode(pic)
	if err != nil {
		return nil, err
	}
	thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom)

	return thumb, nil
}


pic, header, err := r.FormFile("avatar") 
// check error
defer pic.Close()

答案1

得分: 4

pic.Seek(0,0)在解码之前修复了问题。

英文:

pic.Seek(0,0) before the decode fixed the issue.

huangapple
  • 本文由 发表于 2015年8月25日 07:38:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/32193395.html
匿名

发表评论

匿名网友

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

确定