I am rewriting with golang a script I originally wrote in python. The function I am trying to recreate currently takes one image (a coloured overlay) and pastes it on a background (a map) of the same size, with 50% transparency. The desired output, as produced by my python script, is:
The golang code I have written to try to replicate this in golang, with reference to this stackoverflow thread.
In main.go
// overlayImg is type image.Image, consists of the coloured overlay
overlayImg = lib.AddMap(overlayImg)
// lib.SaveToRecords is a function that saves image.Image overlayImg to path specified by string download.FileName
lib.SaveToRecords(overlayImg, download.FileName)
In package myproject/lib
func AddMap(i image.Image) image.Image{
// mapFile is the background map image
mapFile, err := os.Open("./res/map.png")
if err != nil { panic(err) }
mapImg, _, err := image.Decode(mapFile)
if err != nil { panic(err) }
mask := image.NewUniform(color.Alpha{128})
canvas := image.NewRGBA(mapImg.Bounds())
draw.Draw(canvas, canvas.Bounds(), mapImg, image.Point{0, 0}, draw.Src)
draw.DrawMask(canvas, canvas.Bounds(), i, image.Point{0, 0}, mask, image.Point{0, 0}, draw.Over)
return canvas
}
However, the resulting image is produced with a sort of 'glitch' in parts of the coloured overlay. This colour glitch is reliably reproduced on each run of the script, even with different overlays (the map stays the same throughout, of course).
How do I get rid of the 'glitch'?
Things I have tried:
- Using
draw.Draw
in place ofdraw.DrawMask
withdraw.Over
as the 'op' setting. Results in same colour 'glitch', but without transparency.
- Using
draw.DrawMask
, except withdraw.Src
as the 'op' setting. Result:
- Using
draw.Draw
in place ofdraw.DrawMask
, and withdraw.Src
as the 'op' setting. This was with a slightly different overlay image. Result:
Update
I've tried assigning mask := image.NewUniform(color.Alpha16{32767})
in place of mask := image.NewUniform(color.Alpha{128})
according to putu's comment. Glitch still appears. Additionally, this glitch is not as consistent as I thought, showing up at only roughly 10% of the time. It seems the glitch shows up depending on the content of the image pasted unto the background.
Update 2
Originally, mapImg
was of type *image.NRGBA, i
and canvas
of type *image.RGBA. Once again following the advice in the comments, I converted mapImg
to type *image.RGBA to match with the rest. To do this, I used the following few lines of code:
mapImg, _, err := image.Decode(mapFile)
mapImgRGBA := image.NewRGBA(mapImg.Bounds())
draw.Draw(mapImgRGBA, mapImgRGBA.Bounds(), mapImg, image.Point{0, 0}, draw.Src)
// Use mapImgRGBA in place of mapImg from here
Still don't work: