Получение RGB-значений определенного пикселя из HBITMAP

0

Как я могу получить определенные RGB-значения пикселей из HBITMAP? Я пробовал читать подобные сообщения в StackOverflow, но ни одна из них не подходит для этой проблемы. Код ниже, кажется, получает значение RGB для другой позиции (а не желаемой) в HBITMAP.

    int width = rc.right - rc.left;
    int height = rc.bottom - rc.top;

    HDC hdcSource = hdc; // the source device context
    HBITMAP hSource = hbmp; // the bitmap selected into the device context

    BITMAPINFO MyBMInfo = {0};
    MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);

    // Get the BITMAPINFO structure from the bitmap
    if(0 == GetDIBits(hdcSource, hSource, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
    {
        // error handling
    }

    // create the pixel buffer
    BYTE* Pixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];

    // We'll change the received BITMAPINFOHEADER to request the data in a
    // 32 bit RGB format (and not upside-down) so that we can iterate over
    // the pixels easily. 

    // requesting a 32 bit image means that no stride/padding will be necessary,
    // although it always contains an (possibly unused) alpha channel
    MyBMInfo.bmiHeader.biBitCount = 32;
    MyBMInfo.bmiHeader.biCompression = BI_RGB;  // no compression -> easier to use
    // correct the bottom-up ordering of lines (abs is in cstdblib and stdlib.h)
    MyBMInfo.bmiHeader.biHeight = abs(MyBMInfo.bmiHeader.biHeight);

    // Call GetDIBits a second time, this time to (format and) store the actual
    // bitmap data (the "pixels") in the buffer lpPixels
    if(0 == GetDIBits(hdcSource, hSource, 0, MyBMInfo.bmiHeader.biHeight,
                      Pixels, &MyBMInfo, DIB_RGB_COLORS))
    {
        // error handling
    }

    int PixelX = 221;
    int PixelY = 14;

    cout << "R: " << (int)Pixels[4*((PixelX-1)+(PixelY-1)*width)] << " | G: " << (int)Pixels[4*((PixelX-1)+(PixelY-1)*width)+1] << " | B: " << (int)Pixels[4*((PixelX-1)+(PixelY-1)*width)+2] << endl;

EDIT (с решением user1118321)

height-1, потому что y начинается с 0, а не 1.

cout << "R: " << (int)Pixels[4*((PixelX)+(height-1-(PixelY))*width)] << " | G: " << (int)Pixels[4*((PixelX)+(height-1-(PixelY))*width)+1] << " | B: " << (int)Pixels[4*((PixelX)+(height-1-(PixelY))*width)+2] << endl;
  • 1
    Вы ищете GetPixel ?
  • 0
    GetPixel работает очень медленно, поэтому я использую HBITMAP, чтобы получить все пиксели в массив.
Показать ещё 12 комментариев
Теги:
rgb
pixel
bitmap
hbitmap

1 ответ

0
Лучший ответ

Растровые изображения Windows сохраняют свой пиксель, начинающийся в левом нижнем углу, при этом Y увеличивается вверх. Попробуйте использовать ((height - 1) - PixelY) вместо просто PixelY и посмотреть, поможет ли это.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню