【发布时间】:2016-09-19 15:57:39
【问题描述】:
我有一个名为 SpriteImage 的结构,其定义如下:
type SpriteImage struct {
dimentions image.Point
lastImgPosition image.Point
sprite *image.NRGBA
}
在我的流程中,我首先启动一个新的这样的结构:
func NewSpriteImage(width, height int) SpriteImage {
c := color.RGBA{0xff, 0xff, 0xff, 0xff}
blankImage := imaging.New(width, height, c)
return SpriteImage{
dimentions: image.Point{X: width, Y: height},
lastImgPosition: image.Point{X: 0, Y: 0},
sprite: blankImage,
}
}
然后我像这样向这个 SpriteImage 添加图像:
func (s *SpriteImage) AddImage(img image.Image) error {
imgWidth := img.Bounds().Dx()
imgHeight := img.Bounds().Dy()
// Make sure new image will fit into the sprite.
if imgWidth != s.dimentions.X {
return fmt.Errorf("image width %d mismatch sprite width %d", imgWidth, s.dimentions.X)
}
spriteHeightLeft := s.dimentions.Y - s.lastImgPosition.Y
if imgHeight > spriteHeightLeft {
return fmt.Errorf("image height %d won't fit into sprite, sprite free space %d ", imgHeight, s.dimentions.Y)
}
// add image to sprite
s.sprite = imaging.Paste(s.sprite, img, s.lastImgPosition)
// update next image position within sprite
s.lastImgPosition = s.lastImgPosition.Add(image.Point{X: 0, Y: imgHeight})
return nil
}
最后,我想把这个SpriteImage 编码为JPEG。但这似乎不起作用。 native JPEG Encode function 占用了一个图像,但我有一个 image.NRGBA。所以我像这样使用github.com/disintegration/imaging lib:
func (s SpriteImage) GetBytes() ([]byte, error) {
var b bytes.Buffer
w := bufio.NewWriter(&b)
if s.sprite == nil {
return nil, fmt.Errorf("sprite is nil")
}
if err := imaging.Encode(w, s.sprite, imaging.JPEG); err != nil {
return nil, err
}
return b.Bytes(), nil
}
然而,返回的字节实际上并不是JPEG。本机 Go JPEG 库不会将这些字节解码为 Go 图像结构。如果我尝试像这样将这些字节解码为图像:
m, _, err := image.Decode(reader)
if err != nil {
log.Fatal(err)
}
我错了:
image: unknown format
有什么想法吗?
【问题讨论】: