Golang : Set image canvas or background to transparent
Putting this down here for my own future reference. Maybe useful to you too. Anyway, basically what I need is to make an image canvas or background to transparent before drawing over it.
For example, I need to set the foreground color to black and set the background to transparent :
foreGroundColor := image.NewUniform(black)
backGroundColor := image.Transparent
backgroundWidth := 700
backgroundHeight := 50
background = image.NewRGBA(image.Rect(0, 0, backgroundWidth, backgroundHeight))
draw.Draw(background, background.Bounds(), backGroundColor, image.ZP, draw.Src)
// draw something with foreGroundColor.....
alternatively, this method will work as well.
// make every pixel transparent
for y := 0; y < backgroundHeight; y++ {
for x := 0; x < backgroundWidth; x++ {
background.Set(x, y, image.Transparent)
}
}
To test, save the background to a PNG file.
// Save that background image to PNG.
imgFile, err := os.Create("background.png")
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
defer imgFile.Close()
buff := bufio.NewWriter(imgFile)
err = png.Encode(buff, background)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
err = buff.Flush()
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
fmt.Println("Save to background.png")
Remember...... that JPEG does not support transparency.
Happy coding!
References:
https://www.socketloop.com/references/golang-image-alpha-set-and-setalpha-functions-examples
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+45.3k Golang : Use wildcard patterns with filepath.Glob() example
+16k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+13.6k Golang : Read from buffered reader until specific number of bytes
+13.1k Python : Convert IPv6 address to decimal and back to IPv6
+9.2k Golang : Capture text return from exec function example
+11.3k Golang : Simple image viewer with Go-GTK
+8.9k Golang : Gorilla web tool kit schema example
+27.1k Golang : Force your program to run with root permissions
+7.4k CloudFlare : Another way to get visitor's real IP address
+17.4k Golang : When to use init() function?
+5.3k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+9.4k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?