使用std :: vector保存BMP像素图

时间:2019-04-30 05:57:28

标签: c++ image bmp

我正在使用std :: vector保存BMP图像的像素图:

struct BGR {
  BYTE &operator[](const BMPCOLORS &color)
  {
    switch (color) {
      case BLUE: return b;
      case GREEN: return g;
      case RED: return r;
    }
    throw ERROR_OUT_OF_BOUNDS;
  }

  DWORD operator()() //return rgb
  {
    return static_cast <DWORD> ((r << 16) | (g << 8) | b);
  }

  BGR()
  : b(0), g(0), r(0)
  {}

  BGR(const BYTE *BGR) : b(BGR[0]), g(BGR[1]), r(BGR[2]) {}
  BGR(BYTE blue, BYTE green, BYTE red) : b(blue), g(green), r(red) {}
  BYTE b, g, r;
};

读取像素图的功能如下:

int BMPimage::ReadImagePixels(void)
{
  if (!my_image_->working_file.is_open())
    return BMP_ERR_READING_FILE;

  DWORD height = my_image_->height;
  DWORD width = my_image_->width;

  BYTE pad_offset = static_cast <BYTE> (( ((width * 3 + 3) & static_cast <unsigned int> (~3)) - (width * 3) ) * sizeof(BYTE));
  BGR temp;

  my_image_->working_file.seekg(my_image_->file_header->bfOffBits);

  for (unsigned int row = 0; row < width; row++)
  {
    for (unsigned int col = 0; col < height; col++)
    {
        my_image_->working_file.read(reinterpret_cast <char*> (&temp), sizeof(BGR));
        pixels.push_back(temp);
    }
    my_image_->working_file.seekg(pad_offset, std::ios::cur);
  }

  return BMP_OK;
}

my_image_->heightmy_image_->width从BITMAPINFOHEADER中获取值,因此它应该是正确的(我已经检查了读取BMP标头的功能,并且是正确的)。

但是在某些情况下,如果图像类型正确(24位格式和V3 Microsoft版本,则没有任何压缩),我会得到超出范围的错误:

terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check: __n (which is 262144) >= this->size() (which is 262144)

我得到的功能示例:

int ImgEdit::make_black_and_white()
{
    int width = static_cast<int> (bmpImg->get_width());
    int height = static_cast<int> (bmpImg->get_height());
    int avg;

    for (int row = 0; row < width; row++)
    {
        for (int col = 0; col < height; col++)
        {
            avg = (bmpImg->pixels.at(static_cast<unsigned long> ( (row * width) + col)).r +
            bmpImg->pixels.at(static_cast<unsigned long> ( (row * width) + col)).g +
            bmpImg->pixels.at(static_cast<unsigned long> ( (row * width) + col)).b) / 3;
            bmpImg->pixels.at(static_cast<unsigned long> ( (row * width) + col)).r = static_cast<unsigned char>(avg);
            bmpImg->pixels.at(static_cast<unsigned long> ( (row * width) + col)).g = static_cast<unsigned char>(avg);
            bmpImg->pixels.at(static_cast<unsigned long> ( (row * width) + col)).b = static_cast<unsigned char>(avg);
        }
    }

    return 0;
}

如果我尝试使用try-catch,则会得到黑白结果图像,左侧带有彩色线。所以我不明白为什么会发生,以及如何使用vector纠正此错误。

P.S。我正在Linux系统上工作,所以我已经定义了:

typedef uint8_t BYTE;
typedef uint16_t WORD;
typedef uint32_t DWORD;

1 个答案:

答案 0 :(得分:0)

terminate called after throwing an instance of 'std::out_of_range'  what():  
vector::_M_range_check: __n (which is 262144) >= this->size() (which is 262144)

发生这种情况是因为std::vector检查您的索引是否在有效范围内。

您的特定问题似乎源于您在循环代码中切换了widthheight