将图像读取为二进制文件

reading an image as a binary file

本文关键字:二进制文件 读取 图像      更新时间:2023-10-16

我在codeproject上读到了关于这个项目的文章。它将图像作为二进制对象读取,然后检查其标头的前10个字节。我写了以下代码在Windows机器上运行:

int main () {
  std::ifstream is ("warren.jpg", std::ifstream::binary);
  if (is) {
    // get length of file:
   // is.seekg (0, is.end);
    int length = 11;
    is.seekg (0, is.beg);
    char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... "<<endl;
    char c='b';
    for(int i=0;i<11;i++)
    {
        is>>c;
    cout<<c<<endl;  //this just prints b 10 times
    }
    // read data as a block:
    is.read (buffer,length-1);
    buffer[length-1]= '';
    if (is)
      std::cout << "all characters read successfully.";
    else
      std::cout << "error: only " << is.gcount() << " could be read";
    is.close();
    cout<<"data is "<<buffer<<endl;
    // ...buffer contains the entire file...
    delete[] buffer;
  }
  return 0;
}

输出为:

Reading 11 characters...
b
b
b
b
b
b
b
b
b
b
b
error: only 0 could be readdata is

所以,我知道第一行

std::ifstream是("warren.jpg",std::ifnstream::binary);

在输入if子句时成功。但在那之后,没有接收到任何作为输入的内容。我知道,由于它是二进制输入,所以不应该使用像is>>c这样的格式化输入。但我只是在是.read()不成功时才写这篇文章。

有人能告诉我问题出在哪里吗?

您将不得不使用以下两个ios::binary | ios::in标志打开您的文件:

std::ifstream ifs (L"c:\james.rar", std::ios::binary | std::ios::in);