写入图像

Writing to an image

本文关键字:图像      更新时间:2023-10-16

我正在尝试从HTTP流中提取图像。我要求使用 C++ 而不是其他库,除了libpcap来捕获数据包。这是我正在做的事情:

if ((tcp->th_flags & TH_ACK) != 0) {
                i = tcp->th_ack;
                const char *payload = (const char *) (packet + SIZE_ETHERNET + size_ip + size_tcp);
                size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp);
                std::string temp(payload);
                dict.insert(std::pair<u_int,std::string>(tcp->th_ack,temp));
        }

然后我连接所有具有相同 ACK 编号的数据包:

 std::string ss;
 for(itt=dict.begin(); itt!= dict.end(); ++itt) {
                std::string temp((*itt).second);
                ss.append(temp);
  }
  std::ofstream file;
  file.open("image.jpg", std::ios::out | std::ios::binary)
  file << ss;
  file.close();

现在,当我将ss写入文件时,文件的大小远小于传输的图像。这是编写二进制文件的正确方法吗?

我正在尝试在C++中执行此操作

使用 std::string

会在第一个以 null 结尾的字符处切断数据(即使 std::string 不是以 null 结尾的字符串)。std::string 的构造函数采用 char* 并假定一个以 null 结尾的字符串。这是一个证明:

char sample [] = {'a', 'b', '', 'c', 'd', '', 'e'};
std::string ss(sample);

您应该使用 std::vector 来存储数据。