【问题标题】:Get pixel color from bitmap data at specified coords [x, y]从指定坐标 [x, y] 的位图数据中获取像素颜色
【发布时间】:2015-05-27 13:30:01
【问题描述】:

我想获取光栅坐标上的像素颜色,例如:

[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 位。

【问题讨论】:

  • 应该是height - 1 - y
  • 我也试过了,但它仍然返回错误的值。

标签: c++ image bitmap getpixel


【解决方案1】:

对于位深度 = 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];
...

【讨论】:

  • 谢谢,现在我想发布解决方案,我看到了你的答案 :) 它现在对我有用,代码如下:pastebin.com/MYHVuvZq 无论如何谢谢你的回答!你能解释一下这是什么吗:(align - 1)) &amp; ~(align - 1);
  • @ProXicT 如果需要,四舍五入到二的下一个幂是一个古老的技巧。 align 必须是 2 的幂。在这种情况下不需要除法/移位,AND 与 NOT 操作一起清除低位。
  • 哦,谢谢,但我仍然不知道为什么它需要在那里。为什么不把 16 放在 const 初始化中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2013-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
相关资源
最近更新 更多