Convert image.Image to image.NRGBA

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
}

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)

Tags:

Image

Go