Locking a GDI+ Bitmap in Native C++?

 ̄綄美尐妖づ 提交于 2019-12-12 18:42:32

问题


I can find many examples on how to do this in managed c++ but none for unmanaged.

I want to get all the pixel data as efficiently as possible, but some of the scan0 stuff I would need more info about so I can properly iterate through the pixel data and get each rgba value from it.

right now I have this:

  Bitmap *b = new Bitmap(filename);
  if(b == NULL)
  {
   return 0;
  }

  UINT w,h;
  w = b->GetWidth();
  h = b->GetHeight();
  Rect *r = new Rect(0,0,w,h);
  BitmapData *lockdat;
 b->LockBits(r,ImageLockModeRead,PixelFormatDontCare,lockdat);

  delete(r);
  if(w == 0 && h == 0)
  {
   return 0;
  }

  Color c;

  std::vector<GLubyte> pdata(w * h * 4,0.0);

  for (unsigned int i = 0; i < h; i++) {
   for (unsigned int j = 0; j < w; j++) {
    b->GetPixel(j,i,&c);

    pdata[i * 4 * w + j * 4 + 0] = (GLubyte) c.GetR();
    pdata[i * 4 * w + j * 4 + 1] = (GLubyte) c.GetG();
    pdata[i * 4 * w + j * 4 + 2] = (GLubyte) c.GetB();
    pdata[i * 4 * w + j * 4 + 3] = (GLubyte) c.GetA();
   }
  }
  delete(b);

  return CreateTexture(pdata,w,h);

How do I use lockdat to do the equivalent of getpixel? Thanks


回答1:


lockdat->Scan0 is a pointer to the pixel data of the bitmap. Note that you really do care what pixel format you ask for, PixelFormatDontCare won't do. Because how you use the pointer is affected by the pixel format. PixelFormat32bppARGB is the easiest, one pixel will be the size of an int, 4 bytes representing alpha, red, green and blue. And the stride will be equal to the width of the bitmap. Making it likely that a simple memcpy() will get the job done. Beware the bitmaps are stored upside-down.




回答2:


Bitmap *m_image = new Bitmap(...) // a 24-bit RGB bitmap

BitmapData bmData;
Rect rect(0, 0, m_image->GetWidth(), m_image->GetHeight());
m_image->LockBits(&rect , ImageLockModeRead , PixelFormat24bppRGB,&bmData  );
memcpy(your_bytes_buffer, bmData.Scan0, min(bmData.Height * bmData.Stride, your_buffer_size));
m_image->UnlockBits(&bmData);


来源:https://stackoverflow.com/questions/2999814/locking-a-gdi-bitmap-in-native-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!