将Win32 Hbitmap转换为WinRT SoftwareBitmap

时间:2018-10-23 01:48:44

标签: c++ winrt-async

我正在实现OCR功能,需要使用softwarebitmap来调用该函数,以防万一我有文件路径,而创建softwarebitmap对象没有问题,但是在某些情况下没有物理文件并且我有win32 hbitmap可以转换为内存缓冲区,可以有人帮我将hbitmap或内存缓冲区转换为softwarebitmap以便调用OCR函数。

std::future<hstring> AsyncSample(const std::wstring &path){

auto file = co_await StorageFile::GetFileFromPathAsync(path);

auto stream = co_await file.OpenAsync(FileAccessMode::Read);

auto decoder = co_await BitmapDecoder::CreateAsync(stream);

auto bitmap = co_await decoder.GetSoftwareBitmapAsync();

auto engine = OcrEngine::TryCreateFromUserProfileLanguages();

auto result = co_await engine.RecognizeAsync(bitmap);

return result.Text();}

1 个答案:

答案 0 :(得分:0)

我找到了解决方法

winrt::Windows::Storage::Streams::IBuffer* 
Conversion::CreateNativeBuffer(LPVOID lpBuffer, DWORD 
nNumberOfBytes)
{
    Microsoft::WRL::ComPtr<NativeBuffer> nativeBuffer;
    Microsoft::WRL::Details::MakeAndInitialize<NativeBuffer> 
    (&nativeBuffer, (BYTE *)lpBuffer, nNumberOfBytes);
    auto iinspectable = (IInspectable *)reinterpret_cast<IInspectable *> 
    (nativeBuffer.Get());
    winrt::Windows::Storage::Streams::IBuffer *buffer = 
    reinterpret_cast<winrt::Windows::Storage::Streams::IBuffer *>(iinspectable);
    return buffer;
}

并在主要功能中

std::future<hstring> getTextFromBufferImage(CHAR *img, DWORD imgLength)
{
    Conversion *tConv = new Conversion();
    static Windows::Storage::Streams::IBuffer *stream;//::IBuffer *iBuffer;
    stream = tConv->CreateNativeBuffer(img, imgLength);
    SoftwareBitmap bitmap(BitmapPixelFormat::Rgba16, 30, 30);
    bitmap.CopyFromBuffer(*stream);
    auto engine = OcrEngine::TryCreateFromUserProfileLanguages();
    auto result = co_await engine.RecognizeAsync(bitmap);

    return result.Text();
}