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
+4.4k Mac OSX : Get disk partitions' size, type and name
+6.1k Golang : Break string into a slice of characters example
+23.6k Golang : Upload to S3 with official aws-sdk-go package
+5.5k List of Golang XML tutorials
+30.5k Golang : Interpolating or substituting variables in string examples
+21.5k Golang : Use TLS version 1.2 and enforce server security configuration over client
+16.1k Golang : Send email and SMTP configuration example
+30k Golang : Generate random string
+9k Golang : Generate random Chinese, Japanese, Korean and other runes
+4.4k Golang : How to pass data between controllers with JSON Web Token
+7.6k Javascript : Put image into Chrome browser's console
+15.8k Golang : Loop each day of the current month example