For a simple gray scale image it is relatively easy to produce the histogram. The exact code of course depends on the in-memory structure of your image. Let's assume you have it in a buffer of width x height bytes by the name pf pBuffer. Sometimes image lines are padded at the end; therefore the variable lineWidth should contain the padded size of each image line.
The code would look like:
unsigned int histo [256];
memset (histo, 0, sizeof histo);
for (int y = 0; y < height; ++y)
{
BYTE* p = pBuffer + y * lineWidth;
for (int x = 0; x < width; ++x)
histo[*p++] += 1;
}
More complexity comes in with the variety of different image formats. But the principal stays the same.