Idiomatic Go for handling any image type with any color type?

Viewed 157

I've found that when I decode images in Go I can get drastically different image types (*image.RGBA, *image.CMYK, *image.Paletted, and more) with conflicting color types (usually paired up to match the image type, e.g. color.RGBA, color.CMYK, color.Palette, etc). It's easy to write brittle code that handles an *image.RGBA perfectly every time, but then it'll panic if the code encounters any other type of image.

I could leave the decoded image as image.Image and use the ColorModel to ensure my colors are always in the right format but I would still need to know what the actual type of the image is to call Set and if it turns out the image was a paletted image, I may not have control over how the finished image looks. A lot of runtime stability can be gained if I can always convert an image into a specific known type before I do anything with it.

Is there an idiomatic Go approach to standardizing image types before doing whatever processing I want to do to them?

EDIT: Another question's answer details how to convert to a target image type but I'm unsure how "idiomatic" it is vs how "duct tape" it is. It lead me to write this:

func ConvertToRGBA(img image.Image) (rgba *image.RGBA) {
    var ok bool
    rgba, ok = img.(*image.RGBA)
    if ok {
        return rgba
    }

    b := img.Bounds()
    rgba = image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
    draw.Draw(rgba, rgba.Bounds(), img, b.Min, draw.Src)

    return rgba
}

Is this as good as it gets or am I way off base?

0 Answers
Related