C++使用poco从url加载图像,转换为未签名的char*



我正在学习使用Poco从web加载图像。我找到的代码:

std::string path(uri.getPathAndQuery());
if (path.empty())
path = "/";
const Poco::Net::Context::Ptr context = new Poco::Net::Context(
Poco::Net::Context::CLIENT_USE, "", "", "",
Poco::Net::Context::VERIFY_NONE, 9, false,
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context);
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTTPResponse response;
bool isSuccess = false;
session.sendRequest(request);
std::istream &rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED) {
std::ofstream ofs("Poco_banner.png", std::fstream::binary);
Poco::StreamCopier::copyStream(rs, ofs);
isSuccess = true;
} else {
//it went wrong ?
isSuccess = false;
}

创建文件的本地副本。我需要它具有与stbi_load:相同的功能

unsigned char* localBuffer = stbi_load(path.c_str(), &width, &height, &bpp, 4);

即,不要下载,而是从该在线图像创建一个具有已知宽度和高度的无符号char*localBuffer。非常感谢。

如果提前知道std::ofstream的大小,您可以简单地将其替换为std:stringstreamPoco::MemoryOutputStream。然而,波科并没有任何处理图像的东西。因此,您需要使用不同的库来提取宽度和高度。或者你可以看看这个答案https://stackoverflow.com/a/16725066/1366591以手动提取宽度和高度。使用Poco::ByteOrder将big endian转换为little endian。

此解决方案有效:

Poco::URI uri(path);
std::string path(uri.getPathAndQuery());
if (path.empty())
path = "/";
const Poco::Net::Context::Ptr context = new Poco::Net::Context(
Poco::Net::Context::CLIENT_USE, "", "", "",
Poco::Net::Context::VERIFY_NONE, 9, false,
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(), context);
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, Poco::Net::HTTPMessage::HTTP_1_1);
Poco::Net::HTTPResponse response;
bool isSuccess = false;
session.sendRequest(request);
std::istream &rs = session.receiveResponse(response);
std::cerr << response.getStatus() << " " << response.getReason() << std::endl;

if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED) {
std:string ss;
Poco::StreamCopier::copyToString64(rs, ss);
std::cerr << "string length " << ss.size() << endl;
std::vector<unsigned char> buffer(ss.begin(), ss.end());

m_localBuffer = stbi_load_from_memory(buffer.data(), (int)buffer.size(), &m_width, &m_height, &m_type, 0);
std::cerr << "width: " << m_width << ", height: " << m_height << ", type: " << m_type << "n";

isSuccess = true;
} 
else 
{
//it went wrong ?
isSuccess = false;
}

最新更新