1、需求:
因项目需要将嵌入式端处理后的图像,发送到同一局域网下的服务器上,但嵌入式上内存有限,开启两个线程频繁的将结果图像写入磁盘会导致设备缓存急剧增长,运行时间久了后会崩溃,因此需要不经过文件,直接将内存里的图像数据传输给同一局域网下的服务器。
2、解决方案:
通过linux内存文件系统Ramfs,将图像存入内存文件中,再通过libcurl post图像到服务器。
void url_img(Mat Img,int line,int id,char* url_name,char* save_name)
{
CURL *curl;
//非线程安全,须在主程序中调用
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl)
{
imwrite(save_name,Img);
//文件读取
int length;
FILE* fp;
//以二进制方式打开图像
if ((fp = fopen(save_name, "rb")) == NULL)
{
cout << "Open image failed!" << endl;
exit(0);
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
rewind(fp);
char* ImgBuffer = (char*)malloc(length * sizeof(char));
//将图像数据读入buffer
fread(ImgBuffer, length, 1, fp);
cout << "length : " <<length << endl;
//设置easy handle属性
// specify URL
curl_easy_setopt(curl,CURLOPT_CUSTOMREQUEST,"PUT");
curl_easy_setopt(curl, CURLOPT_URL, url_name);
curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1L);
curl_easy_setopt(curl,CURLOPT_DEFAULT_PROTOCOL,"https");
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: image/jpeg");
curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);
curl_easy_setopt(curl,CURLOPT_POSTFIELDS,ImgBuffer);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, length);
curl_easy_perform(curl);
fclose(fp);
free(ImgBuffer);
ImgBuffer = NULL;
curl_slist_free_all(headers);
}
// 释放资源
curl_easy_cleanup(curl);
curl_global_cleanup();
}
Tips:
当多个线程,同时进行curl_easy_init时,由于会调用非线程安全的curl_global_init,因此导致崩溃。 应该在主线程优先调用curl_global_init进行全局初始化。再在线程中使用curl_easy_init。
https://www.cnblogs.com/moodlxs/articles/2325075.html https://www.cnblogs.com/milton/p/11541260.html
|