imagegograyscalemonochrome

Make the background of a 8-bit monchrome gray image be transparent


Done so far

I have created an 8-bit monochrome Gray image drawn a closed path on it and then filled the closed path with pixels having a 0x44 value. The code is below.


import (
    "image"

    "app/slicer/renderer/gray/drawgray"
)

    // Initialize the graphic context on a gray image
    dest := image.NewGray(image.Rect(0, 0, 297, 210.0))
    gc := drawgray.NewGraphicContext(dest)

    // Set some properties
    gc.SetFillColor(0x44) // Any integer from 0 to 255

    // Draw a closed shape
    gc.BeginPath() // Initialize a new path
    gc.MoveTo(0, 0)
    gc.LineTo(100, 0)
    gc.LineTo(100, 100)
    gc.LineTo(0, 100)
    gc.Close()
    gc.Fill()

    // Save to file
    drawgray.SaveToPngFile("test1--drawgray.png", dest)

Result

The resulting image is as follows:

Resulting image

Question

Transparent background?

The resulting image above makes sense ✔️

But I have one question about the image background. As can be seen, the pixels outside the path are black. They are not transparent. Maybe it's expected for the image.Gray to have a default black background. Since for each pixel, there is only 1 byte of color info. There is no info regarding the alpha or transparency. Am I right? I'm not sure 🙄

Is there a way to make the pixels outside the drawn path be transparent rather than black? By any chance.


Solution

  • As commented by @JimB :

    "image.Gray represents an 8-bit grayscale color" -- there's no alpha channel, hence there is no transparency.