简体   繁体   English

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

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

I want to get pixel color on raster coordinates like for example: 我想在栅格坐标上获得像素颜色,例如:

[0,0] - pixel in first row and first column (top left) [0,0]-第一行和第一列中的像素(左上)

[0,1] - pixel in first row and second column and so on. [0,1]-第一行和第二列中的像素,依此类推。

I'm loading my bitmap like so: 我正在像这样加载我的位图:

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();

and my GetPixel function: 和我的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];
}

I know the data in bitmap are stored up side down, so I wanted to invert it using the y = height - y; 我知道位图中的数据是上下颠倒存储的,所以我想使用y = height - y;将其反转y = height - y; but with this line I only get some values which even are not in the image data array. 但是通过这一行,我只能得到一些甚至不在图像数据数组中的值。 Without inverting the image I get some values which are in the array but they never correspond with the coords given. 不反转图像,我得到了数组中的一些值,但它们从未与给定的坐标相对应。 My bitmap can be 24-bit or 32-bit. 我的位图可以是24位或32位。

For bit depth = 24, 3 bytes are stored. 对于位深度= 24,将存储3个字节。 The padding is not done per pixel, only on each row: 不会对每个像素进行填充,仅对每一行进行填充:

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];
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM