Last active
January 9, 2020 04:23
-
-
Save riyadhalnur/8b5f16e3cc217c36a3006b25b66ec688 to your computer and use it in GitHub Desktop.
Redraw a transparent PNG into one with an opaque background. This particular code will redraw with a white background.
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 ( | |
"image" | |
gcolor "image/color" | |
"image/draw" | |
"github.com/go-playground/colors" | |
) | |
func redrawImage(imgBytes []byte) error { | |
originalImg, _, err := image.Decode(bytes.NewReader(imgBytes)) | |
if err != nil { | |
return err | |
} | |
if _, _, _, a := originalImg.At(0, 0).RGBA(); a == 0 { | |
// default to white; A=0xff is opaque and not white | |
bgColor := &colors.RGBAColor{R: 0xff, G: 0xff, B: 0xff, A: 0xff} | |
// redraw images with transparent background | |
// otherwise only a black image is generated when decoded above | |
// applies to PNGs only. JPEGs don't support transparency | |
dst := image.NewRGBA(originalImg.Bounds()) | |
draw.Draw(dst, dst.Bounds(), image.NewUniform(gcolor.RGBA{ | |
bgColor.R, | |
bgColor.G, | |
bgColor.B, | |
0xff, | |
}), image.Point{}, draw.Src) | |
draw.Draw(dst, dst.Bounds(), originalImg, originalImg.Bounds().Min, draw.Over) | |
originalImg = dst | |
} | |
// do something with the image | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment