Reputation: 345
When I call png.Decode(imageFile)
it returns a type image.Image
. But I can't find a documented way to convert this to an image.NRGBA
or image.RGBA
on which I can call methods like At()
.
How can I achieve this?
Upvotes: 12
Views: 11687
Reputation: 3920
The solution to the question in the title, how to convert an image to image.NRGBA
, can be found in the Go Blog: The trick is to create a new, empty image.NRGBA
and then to "draw" the original image into the NRGBA image:
import "image/draw"
...
src := ...image to be converted...
b := src.Bounds()
m := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(m, m.Bounds(), src, b.Min, draw.Src)
Upvotes: 7
Reputation: 109406
If you don't need to "convert" the image type, and just want to extract the underlying type from the interface, use a "type assertion":
if img, ok := i.(*image.RGBA); ok {
// img is now an *image.RGBA
}
Or with a type switch:
switch i := i.(type) {
case *image.RGBA:
// i in an *image.RGBA
case *image.NRGBA:
// i in an *image.NRBGA
}
Upvotes: 8