// 在所有包含之前定义这个宏 #define WIN32_LEAN_AND_MEAN // for httplib.h #include #include #include #include #include #include "ImageOcr.h" #include "Wchtcr.h" #include "Utilities.h" #include "nlohmann/json.hpp" #include "httplib.h" #include #include #include #include #include #include using json = nlohmann::json; // DLL 入口点 BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: // 初始化代码 break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: // 清理代码 break; } return TRUE; } extern "C" { __declspec(dllexport) const char* rec(const char* pth_img) { thread_local static std::string result; Wchtcr wchtcr; result = wchtcr.rec(pth_img); return result.c_str(); } } // 启动HTTP服务器的函数 void StartHttpServer(int port) { httplib::Server svr; std::atomic totalTasks(0); // 使用原子类型确保线程安全 // 添加POST接口,接收base64编码的图片 svr.Post("/wechatocr", [&totalTasks, &port](const httplib::Request& req, httplib::Response& res) { std::string msg_Warning_waiting = std::vformat("{{\"msg\":\"warning: waiting previous task done. port {}\" }}", std::make_format_args(port)); std::string msg_Err_noParam = std::vformat("{{\"msg\":\"error: not have img param. port {}\" }}", std::make_format_args(port)); std::string msg_Err_genFilename = std::vformat("{{\"msg\":\"error: gen tmp filename fail. port {}\" }}", std::make_format_args(port)); std::string msg_Err_rec_fail = std::vformat("{{\"msg\":\"error: rec fail port {}\" }}", std::make_format_args(port)); try { // while (totalTasks + 1 > 1) { // std::cout << "########## Warning: Max tasks overflow, Total tasks " << totalTasks << " waitting now... " << std::endl; //std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 等待 1 秒 // } if (totalTasks > 0) { res.status = 201; res.set_content(msg_Warning_waiting, "application/json"); return; } std::cout << "********* Received a new task. Total tasks: " << ++totalTasks << std::endl; // 检查Content-Type const auto& content_type = req.get_header_value("Content-Type"); std::string body_content = req.body; // 如果是URL编码的JSON,先解码 if (content_type.find("application/json") != std::string::npos && req.body.find("%") != std::string::npos) { // 使用httplib内置的decode_path函数解码URL编码的内容 body_content = httplib::detail::decode_path(req.body, true); } // 解析请求体中的JSON数据 json request_data = json::parse(body_content); // 获取base64编码的图片数据 std::string base64_image; if (request_data.contains("img")) { base64_image = request_data["img"].get(); } else { --totalTasks; res.status = 500; res.set_content(msg_Err_noParam, "application/json"); return; } std::vector b64_buf = Utilities::Base64Decode_Raw(base64_image); cv::Mat img_orgin = cv::imdecode(b64_buf, -1); char tempPath[MAX_PATH], tempFile[MAX_PATH]; GetTempPathA(MAX_PATH, tempPath); // 获取系统临时目录 if (GetTempFileNameA(tempPath, "TMP", 0, tempFile) == 0) { // "TMP"为前缀,0表示自动生成唯一编号 --totalTasks; res.status = 201; res.set_content(msg_Err_genFilename, "application/json"); return; } strcat_s(tempFile, ".jpg"); cv::imwrite(tempFile, img_orgin); //cv::imshow("原图", img_orgin); //cv::waitKey(0); // 调用rec函数进行OCR识别 std::string result = rec(tempFile); if (result.empty()) { --totalTasks; res.status = 201; res.set_content(msg_Err_rec_fail, "application/json"); return; } json jsn = json::parse(result); jsn["port"] = port; // 添加端口号到结果中 result = jsn.dump(4); --totalTasks; std::cout << "one task done. Total tasks:" << totalTasks << std::endl; // 返回识别结果 res.status = 200; res.set_content(result, "application/json"); // 删除临时文件 std::remove(tempFile); return; } catch (const std::exception& e) { --totalTasks; res.status = 201; std::string error_msg = e.what(); std::string msg_exception = std::vformat("{\"msg\":\"error: server error. {} port {}\" }", std::make_format_args(error_msg, port) ); res.set_content(msg_exception, "application/json"); return; } }); // 添加一个简单的GET接口,用于测试服务器是否正常运行 svr.Get("/", [](const httplib::Request&, httplib::Response& res) { res.set_content("OCR Sever running ....", "text/plain"); }); std::cout << "OCR Sever running ... : " << port << std::endl; svr.listen("0.0.0.0", port); } int main(int argc, char* argv[]) { //Wchtcr wchtcr; // //std::string result = wchtcr.rec("data/0025.jpg"); //json jsn; //std::string jsn_str; // 默认端口号 int port = 7788; // 如果提供了命令行参数,使用第一个参数作为端口号 if (argc > 1) { try { port = std::stoi(argv[1]); if (port <= 0 || port > 65535) { std::cout << "Invalid port number. Using default port 7788." << std::endl; port = 7788; } } catch (const std::exception& e) { std::cout << "Invalid port number format. Using default port 7788." << std::endl; port = 7788; } } // 启动HTTP服务器,使用指定的端口 std::thread server_thread(StartHttpServer, port); // 分离线程,让它在后台运行 server_thread.detach(); do { // 主线程可以做其他事情,或者等待用户输入退出 //std::cout << "ok." << std::endl; std::cin.get(); } while (true); std::string result = rec("t2.jpg"); json jsn; std::string jsn_str; try { jsn = json::parse(result); jsn_str = jsn.dump(4); } catch (const std::exception& e) { std::cerr << "OCR识别异常: " << e.what() << std::endl; return 1; } return 0; }