我正在编写一个 Web API,在 linux 下使用 CGI。一切都很好,使用 gcc。我正在向主机返回图像 (jpeg):std::cout << "Content-Type: image/jpeg\n\n"现在必须发送二进制 jpeg 图像。将图像加载到 char* 缓冲区和 std::cout << buffer;不起作用。我确实得到了一张空图像。我怀疑标准输出在第一个 00 字节处停止。
我从网络服务器收到带有不完整图像的 200 OK。
我打算重定向到设备上打开的文件夹中的文件,但这必须是安全传输,并且知道 url 的任何人都无法访问。
我被难住了!
代码片段如下所示:
std:string imagePath;
syslog(LOG_DEBUG, "Processing GetImage, Image: '%s'", imagePath.c_str());
std::cout << "Content-Type: image/jpeg\n\n";
int length;
char * buffer;
ifstream is;
is.open(imagePath.c_str(), ios::in | ios::binary);
if (is.is_open())
{
// get length of file:
is.seekg(0, ios::end);
length = (int)is.tellg();
is.seekg(0, ios::beg);
// allocate memory:
buffer = new char[length]; // gobble up all the precious memory, I'll optimize it into a smaller buffer later
// OH and VECTOR Victor!
syslog(LOG_DEBUG, "Reading a file: %s, of length %d", imagePath.c_str(), length);
// read data as a block:
is.read(buffer, length);
if (is)
{
syslog(LOG_DEBUG, "All data read successfully");
}
else
{
syslog(LOG_DEBUG, "Error reading jpg image");
return false;
}
is.close();
// Issue is this next line commented out - it doesn't output the full buffer
// std::cout << buffer;
// Potential solution by Captain Obvlious - I'll test in the morning
std::cout.write(buffer, length);
}
else
{
syslog(LOG_DEBUG, "Error opening file: %s", imagePath.c_str());
return false;
}
return true;
最佳答案
正如已经向您指出的那样,您需要使用 write() 而不是 IO 格式化操作。
但您甚至不需要这样做。您无需手动将一个文件复制到另一个文件,一次复制一个缓冲区,届时 iostreams 会很乐意为您做这件事。
std::ifstream is;
is.open(imagePath.c_str(), std::ios::in | std::ios::binary);
if (is.is_open())
{
std::cout << is.rdbuf();
}
差不多就这些了。</p>
关于c++ - Linux CGI Web API - 如何在 C++ 下标准输出二进制 JPEG 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32386972/