从指定坐标[x, y]处的位图数据获取像素颜色

Get pixel color from bitmap data at specified coords [x, y]

本文关键字:位图 数据获取 颜色 像素 坐标      更新时间:2023-10-16

我想在栅格坐标上获得像素颜色,例如:

[0,0] -第一行和第一列(左上角)的像素

[0,1] -第一行和第二列的像素,以此类推。

我正在像这样加载我的位图:

BitsPerPixel = FileInfo[28];
width = FileInfo[18] + (FileInfo[19] << 8);
height = FileInfo[22] + (FileInfo[23] << 8);
int PixelsOffset = FileInfo[10] + (FileInfo[11] << 8);
int size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
Pixels.resize(size);
hFile.seekg(PixelsOffset, ios::beg);
hFile.read(reinterpret_cast<char*>(Pixels.data()), size);
hFile.close();

和我的GetPixel函数:

void BITMAPLOADER::GetPixel(int x, int y, unsigned char* pixel_color)
{
    y = height - y;
    const int RowLength = 4 * ((width * BitsPerPixel + 31) / 32);
    pixel_color[0] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8];
    pixel_color[1] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 1];
    pixel_color[2] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 2];
    pixel_color[3] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 3];
}

我知道位图中的数据是向上向下存储的,所以我想使用y = height - y;来反转它,但是有了这行,我只得到一些甚至不在图像数据数组中的值。不反转图像,我得到数组中的一些值,但它们从不与给定的坐标对应。我的位图可以是24位或32位。

对于bit depth = 24,存储3字节。padding不是按像素填充,而是按行填充:

const int bytesPerPixel = BitsPerPixel / 8;
const int align = 4;
const int RowLength = (width * bytesPerPixel + (align - 1)) & ~(align - 1);
...
pixel_color[0] = Pixels[RowLength * y + x * bytesPerPixel];
...