|
|
#include "ImageOcr.h" |
|
|
#include <Windows.h> |
|
|
#include <fstream> |
|
|
#include <thread> |
|
|
#include <iostream> |
|
|
|
|
|
ImageOcr::ImageOcr(const std::string& path) |
|
|
{ |
|
|
|
|
|
if (path.empty()) |
|
|
_ocrManager = new OcrManager(); |
|
|
else |
|
|
_ocrManager = new OcrManager(path); |
|
|
|
|
|
|
|
|
_ocrManager->StartWeChatOcr(_ocrManager); |
|
|
} |
|
|
|
|
|
ImageOcr::~ImageOcr() |
|
|
{ |
|
|
|
|
|
if (_ocrManager != nullptr) |
|
|
{ |
|
|
_ocrManager->KillWeChatOcr(); |
|
|
delete _ocrManager; |
|
|
_ocrManager = nullptr; |
|
|
} |
|
|
} |
|
|
|
|
|
void ImageOcr::Run(const std::string& imagePath, std::function<void(const std::string&, std::string&)> callback) |
|
|
{ |
|
|
|
|
|
if (callback) |
|
|
_ocrManager->SetOcrResultCallback(callback); |
|
|
|
|
|
|
|
|
unsigned int retryCount = 0; |
|
|
while (retryCount <= MaxRetryTimes) |
|
|
{ |
|
|
try |
|
|
{ |
|
|
_ocrManager->DoOcrTask(imagePath); |
|
|
return; |
|
|
} |
|
|
catch (const std::overflow_error&) |
|
|
{ |
|
|
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
|
|
retryCount++; |
|
|
} |
|
|
catch (const std::exception& ex) |
|
|
{ |
|
|
|
|
|
std::cerr << "OCR Error: " << ex.what() << std::endl; |
|
|
return; |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
static void WriteBytesToFile(const std::string& filePath, const unsigned char* bytes, size_t length) |
|
|
{ |
|
|
std::ofstream fileStream(filePath, std::ios::binary); |
|
|
if (fileStream.is_open()) |
|
|
{ |
|
|
fileStream.write(reinterpret_cast<const char*>(bytes), length); |
|
|
fileStream.close(); |
|
|
} |
|
|
} |
|
|
|
|
|
void ImageOcr::Run(const unsigned char* bytes, size_t length, std::function<void(const std::string&, std::string&)> callback, ImageType imgType) |
|
|
{ |
|
|
|
|
|
char tempPath[MAX_PATH]; |
|
|
GetTempPathA(MAX_PATH, tempPath); |
|
|
|
|
|
std::string extension; |
|
|
switch (imgType) |
|
|
{ |
|
|
case ImageType::Png: extension = "png"; break; |
|
|
case ImageType::Jpeg: extension = "jpeg"; break; |
|
|
case ImageType::Bmp: extension = "bmp"; break; |
|
|
default: extension = "png"; |
|
|
} |
|
|
|
|
|
std::string imgPath = std::string(tempPath) + "generate4wechat." + extension; |
|
|
|
|
|
|
|
|
WriteBytesToFile(imgPath, bytes, length); |
|
|
|
|
|
|
|
|
Run(imgPath, callback); |
|
|
} |