imagegograyscalergbamonochrome

Save RGBA image as an 8-bit grayscale monochrome image


Background

I have this code to write to disk an RGBA image as a PNG file. It works just fine for the ordinary RGBA image for which each pixel has 4 bytes of info for its 4 RGBA component.


import (
    "bufio"
    "image"
    "image/png"
    "os"
)

// SaveToPngFile create and save an image to a file using PNG format
func SaveToPngFile(filePath string, m image.Image) error {
    // Create the file
    f, err := os.Create(filePath)
    if err != nil {
        return err
    }
    defer f.Close()
    // Create Writer from file
    b := bufio.NewWriter(f)
    // Write the image into the buffer
    err = png.Encode(b, m)
    if err != nil {
        return err
    }
    err = b.Flush()
    if err != nil {
        return err
    }
    return nil
}

4 bytes vs 1 byte

RGBA vs 8-bit monochrome

I have manually modified the pixel buffer of my RGBA image so that each pixel has only a 1 byte associated with it and the 1 byte only contains the R component of the RGBA. How can I modify the above code, so that my modified image can be saved to disk and visualized properly as an 8-bit grayscale monochrome like the one listed here:

https://en.wikipedia.org/wiki/List_of_monochrome_and_RGB_color_formats


Solution

  • As recommended by @Volker, I'm switching to image.Gray to store only 1 byte for each pixel. That looks like to be the standard approach.