adjust bitmap image brightness/contrast using c++

后端 未结 2 938
执念已碎
执念已碎 2021-02-06 16:19

adjust image brightness/contrast using c++ without using any other 3rd party library or dependancy

2条回答
  •  长情又很酷
    2021-02-06 17:22

    Image brightness is here - use the mean of the RGB values and shift them.

    Contrast is here with other languages solutions available as well.


    Edit in case the above links die:

    The answer given by Jerry Coffin below covers the same topic and has links that still live.

    But, to adjust brightness, you add a constant value to each for the R,G,B fields of an image. Make sure to use saturated math - don't allow values to go below 0 or above the maximum allowed in your bit-depth (8-bits for 24-bit color)

    RGB_struct color = GetPixelColor(x, y);
    size_t newRed   = truncate(color.red   + brightAdjust);
    size_t newGreen = truncate(color.green + brightAdjust);
    size_t newBlue  = truncate(color.blue  + brightAdjust);
    

    For contrast, I have taken and slightly modified code from this website:

    float factor = (259.0 * (contrast + 255.0)) / (255.0 * (259.0 - contrast));
    RGB_struct color = GetPixelColor(x, y);
    size_t newRed   = truncate((size_t)(factor * (color.red   - 128) + 128));
    size_t newGreen = truncate((size_t)(factor * (color.green - 128) + 128));
    size_t newBlue  = truncate((size_t)(factor * (color.blue  - 128) + 128));
    

    Where truncate(int value) makes sure the value stays between 0 and 255 for 8-bit color. Note that many CPUs have intrinsic functions to do this in a single cycle.

    size_t truncate(size_t value)
    {
        if(value < 0) return 0;
        if(value > 255) return 255;
    
        return value;
    }
    

提交回复
热议问题