簡體   English   中英

從位圖數據中指定坐標[x,y]獲取像素顏色

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

我想在柵格坐標上獲得像素顏色,例如:

[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;將其反轉y = height - y; 但是通過這一行,我只能得到一些甚至不在圖像數據數組中的值。 不反轉圖像,我得到了數組中的一些值,但它們從未與給定的坐標相對應。 我的位圖可以是24位或32位。

對於位深度= 24,將存儲3個字節。 不會對每個像素進行填充,僅對每一行進行填充:

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