Zoltan
Zoltan

Reputation: 315

Golang - Swap PNG channels of a picture using Image and Image/PNG

I'm trying to write a short one, which will read a PNG file, and swap one channel with the other (R,G,B) being the possible choices.

I can't find out however, how to extract the integer from the color.Color object returned by image.At(x,y) . Writing it back would probably easier with image.Set(x,y,color) once i can construct the new RGBA color with the swapped channels.

Here I am now (you can pretty much skip to the last loop):

package main

import (
"flag"
"fmt"
//"image"
"image/color"
"image/png"
"os"
)

type Choice struct {
value string
valid bool
}

func (c *Choice) validate() {
goodchoices := []string{"R", "G", "B"}
for _, v := range goodchoices {
    if c.value == v {
        c.valid = true
    }
}
}

func main() {

var fname string
var c1 Choice
var c2 Choice

flag.StringVar(&c1.value, "c1", "", "The color channel to swap - R or G or B ")
flag.StringVar(&c2.value, "c2", "", "The color channel to swap with - R or G or B ")
flag.StringVar(&fname, "f", "", "A .png image (normal map)")
flag.Parse()

c1.validate()
c2.validate()

if c1.valid == true && c2.valid == true {
    fmt.Println("We could proceed..")
    fmt.Println("Swapping channels:", c1.value, "<->", c2.value, "In", fname) //for testing
} else {
    fmt.Println("Invalid channel... Please use R, G or B.")
    return
}

file, err := os.Open(fname)
if err != nil {
    fmt.Println(err)
    return
}
defer file.Close()

pic, err := png.Decode(file)
if err != nil {
    fmt.Fprintf(os.Stderr, "%s: %v\n", fname, err)
    return
}

b := pic.Bounds()

for y := b.Min.Y; y < b.Max.Y; y++ {
    for x := b.Min.X; x < b.Max.X; x++ {
        col := pic.At(x, y)
        ???? How do I swap the channels in col ???? 
    }
}
}

I'm really new to Go and programming in general, so please consider it in your answer. Thank You.

Upvotes: 5

Views: 2845

Answers (1)

Nick Craig-Wood
Nick Craig-Wood

Reputation: 54089

Hmmm, that was harder than I thought it would be - I wonder if anyone can come up with a better idea!

The problem is that you don't know the concrete type that png.Decode returns - it may return any of the image types. You only have an image.Image interface which doesn't have a Set method.

To get round that, first define an interface which all the Image types which can set pixels satisfies

type ImageSet interface {
     Set(x, y int, c color.Color)
}

Next see whether pic implements that interface (go will panic if it doesn't - use the picSet, ok form if that bothers you)

// Get an interface which can set pixels
picSet := pic.(ImageSet)

Now your loop looks like this - I only swapped red and green so you can see the idea.

for y := b.Min.Y; y < b.Max.Y; y++ {
    for x := b.Min.X; x < b.Max.X; x++ {
        col := pic.At(x, y)
        r, g, b, a := col.RGBA()
        // Swap green and red
        newCol := color.RGBA{uint8(g>>8), uint8(r>>8), uint8(b>>8), uint8(a>>8)}
        picSet.Set(x, y, newCol)
    }
}

I suspect that a high performing version of this would have to use a type switch to determine which image type it was, then have a customized code for each one with uint8s for 24 bit images and uint16s for 48 bit images etc.

Here is the complete working example if you want to have a go. It doesn't work in the playground though - you'll have to download it.


Update: Just noticed your comment. If you know that you have an RGBA image, then you can use a type assertion to get the underlying image which makes things a whole lot easier.

// Get an image.RGBA if it is one
rgba, ok := pic.(*image.RGBA)
if !ok {
    fmt.Println("That wasn't an RGBA!")
    return
}

for y := b.Min.Y; y < b.Max.Y; y++ {
    for x := b.Min.X; x < b.Max.X; x++ {
        // Note type assertion to get a color.RGBA
        col := rgba.At(x, y).(color.RGBA)
        // Swap green and red
        col.G, col.R = col.R, col.G
        rgba.Set(x, y, col)
    }
}

Upvotes: 7

Related Questions