Image.FromHbitmap problem

G

Guest

Folks,

I am having trouble using Image.FromHbitmap. I create a DIBSECTION in
unmanaged code and then pass its handle to the managed code, to use as an
argument for Image.FromHbitmap. The resulting managed Bitmap has the correct
size and so forth but does not contain the right pixel values. For example,
in the following code I create a 150 x 100 bitmap filled with yellow pixels,
and try to display it. What gets displayed is a bitmap filled with black
pixels.

When I modify the unmanaged code so that it displays the bitmap, I get a
bitmap filled with yellow pixels.

I am using VS 2005 and a VGA PPC emulator. Any assistance much appreciated.

managed code:

[DllImport("dplib.dll")]
public static extern IntPtr createBitmap();

Bitmap bmp=Image.FromHbitmap(createBitmap());



private void onPaint(object sender, PaintEventArgs e)
{

Graphics g = e.Graphics;
g.DrawImage(bmp,
new Rectangle(0, 0, bmp.Width, bmp.Height),
new Rectangle(0, 0, bmp.Width, bmp.Height),
GraphicsUnit.Pixel);

}

unmanaged code:

extern "C" __declspec(dllexport)
HBITMAP WINAPI createBitmap() {
BITMAPINFO bmi;
memset(&bmi, 0, sizeof(BITMAPINFO));

bmi.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth=150;
bmi.bmiHeader.biHeight=-100;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 24;
bmi.bmiHeader.biCompression = BI_RGB;

unsigned char* pBits;
HBITMAP hDIBSection = CreateDIBSection(NULL, &bmi, 0,
reinterpret_cast<LPVOID*>(&pBits),NULL,0);

if (pBits) {
unsigned int aligned_bytes_per_scanline =
(((bmi.bmiHeader.biWidth * bmi.bmiHeader.biBitCount)
+ 31) & ~31) >> 3;

for (int y=0; y< -bmi.bmiHeader.biHeight;++y) {
RGBTRIPLE *pScanLine = reinterpret_cast<RGBTRIPLE *>(
pBits + (y * aligned_bytes_per_scanline));
for (int x = 0; x< bmi.bmiHeader.biWidth;++x) {
pScanLine[x].rgbtBlue = 0;
pScanLine[x].rgbtGreen = 255;
pScanLine[x].rgbtRed = 255;
}
}
}


//DeleteObject(hDIBSection);
return hDIBSection;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top