Golang - Exchange PNG image channels using Image and Image / PNG

I am trying to write a short one that will read a PNG file and swap one channel with another (R, G, B), which will become a possible choice.

I cannot learn how to extract an integer from the color.Color object returned by the image .At (x, y). Writing it would be easier with image.Set (x, y, color) when I can build a new RGBA color with exchanged channels.

Here I am right now (you can pretty much skip 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 am really new to Go and programming in general, so please consider this in your answer. Thank.

+5
source share
1 answer

, , , - , - !

, , png.Decode - . image.Image, Set.

, , , ,

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

, pic (go , ) picSet, ok, )

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

: , .

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)
    }
}

, , , , uint8s 24- uint16s 48- ..

, . - .


: . , RGBA, , , .

// 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)
    }
}
+7

All Articles