Zhao Lang
Zhao Lang

Reputation: 21

go decode image unsupported type error

I'm trying to open a png image using the built in "image" package as such:

infile, err := os.Open(filename)
image.RegisterFormat("png", "png", png.Decode, png.DecodeConfig)
src, _, err := image.Decode(infile)

The image.Decode function is producing an error of unsupported type *image.RGBA. Anyone have any insight into this error?

I also tried this with a JPEG with the corresponding registration:

image.RegisterFormat("png", "png", png.Decode, png.DecodeConfig)
src, _, err := image.Decode(infile)

Which results in unsupported type *image.YCbCr. Very confusing as the image itself is in RGB.

Edit: also tried just importing image/jpeg and image/png, without using image.RegisterFormat, but still getting the same errors.

Edit #2: Apologies, the error I was getting was not even coming from the Decode function. The images decode properly.

Upvotes: 2

Views: 1830

Answers (2)

Pravin Divraniya
Pravin Divraniya

Reputation: 4384

Great answer by @icza. Make it simple just import packages "image/jpeg" and "image/png" (If we have to work with both image format.Otherwise import only specific package you gonna use either "image/jpeg" or "image/png"). It works for me.

import (
    ...
    .
    . 
    _ "image/jpeg"
    _ "image/png"
    .
    . 
    ....
)

Upvotes: 0

icza
icza

Reputation: 418435

First the mistakes:

You make a mistake when registering the formats.

The PNG magic is not "png" but "\x89PNG\r\n\x1a\n". So registration is:

image.RegisterFormat("png", "\x89PNG\r\n\x1a\n", png.Decode, png.DecodeConfig)

The JPEG magic is not "jpeg" but "\xff\xd8". JPEG registration:

image.RegisterFormat("jpeg", "\xff\xd8", jpeg.Decode, jpeg.DecodeConfig)

BUT don't do this!

Simply import the image/png and image/jpeg packages, the package init functions do this automatically for you. You may use the blank identifier if you don't use the packages (and you only do this for the initialization "side-effect"):

import (
    _ "image/png"
    _ "image/jpeg"
)

After the above imports, you will be able to decode PNG and JPEG images.

Upvotes: 4

Related Questions