title: Encoding an Image to JPEG in Go
body: <p>I have a struct called SpriteImage which is defined like this:</p>
  
  <pre><code>type SpriteImage struct {
      dimentions      image.Point
      lastImgPosition image.Point
      sprite          *image.NRGBA
  }
  </code></pre>
  
  <p>In my flow, I first initiate a new such struct:</p>
  
  <pre><code>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,
      }
  }
  </code></pre>
  
  <p>And then I add images to this SpriteImage like so:</p>
  
  <pre><code>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 &gt; 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
  }
  </code></pre>
  
  <p>Eventually, I want to take this <code>SpriteImage</code> and encode it as <code>JPEG</code>. But it doesn't seem to work. The <a href="https://golang.org/src/image/jpeg/writer_test.go" rel="noreferrer">native JPEG Encode function</a> takes up an image, but I have an image.NRGBA. So I'm using <code>github.com/disintegration/imaging</code> lib like so:</p>
  
  <pre><code>func (s SpriteImage) GetBytes() ([]byte, error) {
      var b bytes.Buffer
      w := bufio.NewWriter(&amp;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
  }
  </code></pre>
  
  <p>However is seems that the bytes returned are not in fact <code>JPEG</code>. The native Go JPEG lib will not decode those bytes to a Go image struct. If I try to decode those bytes to image like so:</p>
  
  <pre><code>     m, _, err := image.Decode(reader)
       if err != nil {
          log.Fatal(err)
       }
  </code></pre>
  
  <p>I'm getting err:</p>
  
  <p><code>image: unknown format</code></p>
  
  <p>Any ideas?  </p>