在 Go 中将图像编码为 JPEG

orc*_*man 6 jpeg imaging go

我有一个名为 SpriteImage 的结构,其定义如下:

type SpriteImage struct {
    dimentions      image.Point
    lastImgPosition image.Point
    sprite          *image.NRGBA
}
Run Code Online (Sandbox Code Playgroud)

在我的流程中,我首先启动一个新的此类结构:

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,
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我将图像添加到该 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
}
Run Code Online (Sandbox Code Playgroud)

最终,我想将SpriteImage其编码为JPEG. 但这似乎不起作用。本机JPEG编码函数占用图像,但我有一个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
}
Run Code Online (Sandbox Code Playgroud)

然而,似乎返回的字节实际上并非如此JPEG。本机 Go JPEG 库不会将这些字节解码为 Go 图像结构。如果我尝试将这些字节解码为图像,如下所示:

     m, _, err := image.Decode(reader)
     if err != nil {
        log.Fatal(err)
     }
Run Code Online (Sandbox Code Playgroud)

我犯了错误:

image: unknown format

有任何想法吗?

edu*_*911 2

也许需要检查一下:image: unknown format当您不包含image/jpeg库并专门用它进行解码时,这是一个常见错误:

import (
  "image/jpeg"
  "io"
)

...    
  img, err := jpeg.Decode(r)
  if err != nil {
     return err
  }
...
Run Code Online (Sandbox Code Playgroud)

有些尝试使用image.Decode,但您仍然需要包含该image/jpeg库。

我相信它适用于盲人包括:

import (
  _ "image/jpeg"
  "image"
  "io"
)

...    
  img, err := image.Decode(r)
  if err != nil {
     return err
  }
...
Run Code Online (Sandbox Code Playgroud)