Image transformation. Image to image.NRGBA

When I call png.Decode(imageFile)

it returns the type image.Image

. But I can't find a documented way to convert this to image.NRGBA

or image.RGBA

on which I can call methods like At()

.

How can I achieve this?

+6


source to share


2 answers


If you don't need to "convert" the type of the image and just want to extract the base type from the interface, use a "type assertion":

if img, ok := i.(*image.RGBA); ok {
    // img is now an *image.RGBA
}

      



Or with a switch like:

switch i := i.(type) {
case *image.RGBA:
    // i in an *image.RGBA
case *image.NRGBA:
    // i in an *image.NRBGA
}

      

+5


source


The solution to the question in the title, how to convert an image to image.NRGBA

, can be found on the Go blog : the trick is to create a new empty one image.NRGBA

and then "paint" the original image to an 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)

      

0


source







All Articles