Search code examples
c#imageencodingpixel

GrayScale Pixels / value relation


I have to save lots of data and i've chosen to save them as an image in which

each pixel will have an value in [0,1] (inclusiv).{0->white/1->black).

How can i encode a value [0,1] into a pixel color?


Solution

  • Generally image data uses R,G,B, which are stored as unsigned bytes (e.g. they have a value from 0-255). Therefore, you need to multiply your [0,1] value by 255 to get the corresponding pixel value. Depending on how you are creating your image, you may need this as a byte array, or as a Color object:

    float colorvalue = 0.6f;
    // as a byte array:
    byte[] rgb = new byte[3];
    rgb[0] = (byte)(colorvalue * 255);
    rgb[1] = (byte)(colorvalue * 255);
    rgb[2] = (byte)(colorvalue * 255);
    //as a color:
    Color newcol = Color.FromArgb((int)(colorvalue * 255), (int)(colorvalue * 255), (int)(colorvalue * 255));