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
+5.3k Clean up Visual Studio For Mac installation failed disk full problem
+15.8k Golang : Get sub string example
+8.1k Golang : Count leading or ending zeros(any item of interest) example
+5.2k Golang *File points to a file or directory ?
+31.5k Golang : Convert an image file to []byte
+7.2k Golang : Create zip/ePub file without compression(use Store algorithm)
+11.5k Golang : Verify Linux user password again before executing a program example
+6.3k Unix/Linux : How to get own IP address ?
+13.7k Golang : Compress and decompress file with compress/flate example
+26.1k Golang : Convert(cast) string to uint8 type and back to string
+12.1k Golang : Print UTF-8 fonts on image example
+16.4k Golang : Read integer from file into array