Click here to Skip to main content
15,905,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote the ProccessImage function,but when I use it with an image of size 1680*1050 ,the result is an error(memory access)
I don't understand why?


C++
HBITMAP ProccessImage(HBITMAP hBitmap )
{
	BITMAP Bmp;
	GetObject(hBitmap,sizeof(Bmp),&Bmp);
	LPDWORD pixels = (LPDWORD)Bmp.bmBits;
		for(int row = 0; row < Bmp.bmHeight; ++row)
			for(int col = 0; col < Bmp.bmWidth; ++col)
				pixels[row * Bmp.bmWidthBytes / 4 + col] = RGB(0,127,255) ;
		return hBitmap;
}
Posted

1 solution

I don't see anything wrong with your example, except that you assume that this is a bitmap of 4-byte pixels. If the pixel type is smaller that would explain the access violation. A test of bmBitsPixel would give you certainty that this is the cause.

Edited: Ok, now that we know that you have 3 bytes per pixel we need to rearrange your loop a little. First of all, we have to define the pointer to the current pixel as a byte pointer instead of DWORD pointer. Then we step in 3-byte increments across a scan line:

for(int row = 0; row < Bmp.bmHeight; ++row)
{
    BYTE* p = ((BYTE*) Bmp.bmBits) + row * Bmp.bmWidthBytes;
    for(int col = 0; col < Bmp.bmWidth; ++col)
    {
        *p++ = 255; // blue
        *p++ = 127; // green
        *p++ = 0;   // red
    }
}


As you see, in this way we can also avoid to calculate the pixel's address for every single pixel. Note that it is necessary to recalculate the pixel pointer for every row, because at the end of each row there might occur several slack bytes to fill up to the next even boundary. That is why the BITMAP structure holds the member bmWidthBytes to tell us exactly how long a row is.
 
Share this answer
 
v2
Comments
PE32_64 21-Apr-12 4:11am    
It is 24 Bits Per Pixel.
Where 's the problem?
PE32_64 21-Apr-12 4:11am    
And how can I solve it?
nv3 21-Apr-12 5:09am    
Ok, that explains it. See the addition to the solution above that shows how to deal with 3-byte / pixel images. I hope that gets you going.
PE32_64 21-Apr-12 6:05am    
Thank you very much Mr nv3
I got it.
nv3 21-Apr-12 7:11am    
You are welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900