2

I am loading a jpeg from the disk, and I would like to do some RGBA operations on it.

However, since the jpeg is not RGBA, i get an error when I try to use it as such:

thumbnail,err:=jpeg.Decode(imageAsReader)
...
return thumbnail.(*image.RGBA)

yeileds the error:

interface conversion: image.Image is *image.YCbCr, not *image.RGBA

Is there an easy way to convert the image to RGBA once I have loaded it in memory? (Other operations are in RGBA later on, so that is the color model I want to use in memory).

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
eshalev
  • 3,033
  • 4
  • 34
  • 48
  • You could create a new RGBA image with the same bounds, iterate the YCbCr image pixel by pixel using `.At()` (which returns an RGBA `Color` value), and copy it to the RGBA image. Posting as a comment because I'm really hoping there's a better answer out there for you from someone who has used the `image` package. – Adrian Nov 28 '17 at 16:03
  • And you can see an example of how to draw an image onto another at the end of this answer: [Change color of a single pixel - Go lang image](https://stackoverflow.com/questions/36573413/change-color-of-a-single-pixel-go-lang-image/36577076#36577076) – icza Nov 28 '17 at 16:17

1 Answers1

4

As the comments suggest, you have to create a new image and draw into it: b := thumbnail.Bounds() m := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) draw.Draw(m, m.Bounds(), thumbnail, b.Min, draw.Src)

YCbCr is a sub-sampled image, so it doesn't map directly to the 4-bytes-per-pixel of RGBA.

Graham King
  • 5,710
  • 3
  • 25
  • 23