Created
July 26, 2021 19:21
-
-
Save brunolkatz/648fac1b1fae2cc3be7c605fbd59c80d to your computer and use it in GitHub Desktop.
change a pixel #ff00ff color to transparency with golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"image/color" | |
"image/png" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
type Changeable interface { | |
Set(x, y int, c color.Color) | |
} | |
var ( | |
PinkTransparecyColor = color.RGBA{R: 255, B: 255, A: 255} // #ff00ff | |
) | |
func main() { | |
imgfile, err := os.Open("spritesheet.png") | |
if err != nil { | |
panic(err.Error()) | |
} | |
defer imgfile.Close() | |
img, err := png.Decode(imgfile) | |
if err != nil { | |
panic(err.Error()) | |
} | |
if cimg, ok := img.(Changeable); ok { | |
for y := 0; y < img.Bounds().Max.Y; y++ { | |
for x := 0; x < img.Bounds().Max.X; x++ { | |
if img.At(x, y) == PinkTransparecyColor { | |
cimg.Set(x, y, color.RGBA{0, 0, 0, 0}) | |
} | |
} | |
} | |
ext := filepath.Ext("spritesheet.png") | |
name := strings.TrimSuffix(filepath.Base("spritesheet.png"), ext) | |
fg := &os.File{} | |
fg, err = os.Create(fmt.Sprintf("%s_go_removed_transparency%s", name, ext)) | |
if err != nil { | |
panic(err) | |
} | |
defer fg.Close() | |
err = png.Encode(fg, img) | |
if err != nil { | |
panic(err) | |
} | |
}else{ | |
panic("encoded image not support set(x, y, color.Color) function") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment