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
+15.9k Golang : Read large file with bufio.Scanner cause token too long error
+16.4k Golang : Get IP addresses of a domain name
+25.7k Golang : Daemonizing a simple web server process example
+11.6k How to tell if a binary(executable) file or web application is built with Golang?
+4.9k Nginx and PageSpeed build from source CentOS example
+21.5k Golang : Encrypt and decrypt data with TripleDES
+6.6k Golang : Reverse by word
+5.8k Golang : Denco multiplexer example
+8.3k Your page has meta tags in the body instead of the head
+28.1k Golang : Connect to database (MySQL/MariaDB) server
+9.5k Golang : Validate IPv6 example
+14k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error