【问题标题】:How to create WritebleBitmap from a resource image with C++ for Windows Metro app?如何使用 C++ 为 Windows Metro 应用程序从源图像创建 WriteableBitmap?
【发布时间】:2012-07-20 14:59:48
【问题描述】:

我可以使用以下代码从资源 JPG 图像文件轻松创建 BitmapImage...

Windows::Foundation::Uri^ uri = ref new Windows::Foundation::Uri(L"ms-appx:///Hippo.JPG");
Imaging::BitmapImage^ image = ref new Imaging::BitmapImage(uri);

但是 WritableBitmap 不接受 Uri。我看到了一个 SetSource 方法,但它需要一个 IRandomaccessStream 而不是 Uri。而且我不知道如何从 JPG 文件创建一个。我一遍又一遍地在网上搜索,但找不到一个直截了当的答案。任何帮助将不胜感激。

我想要这样的东西......

Windows::UI::Xaml::Media::Imaging::WriteableBitmap image = ref new Windows::UI::Xaml::Media::Imaging::WriteableBitmap();
image->SetSource(somehowGetRandomAccessStreamFromUri);

但是,如何从 uri 中获取 IRandomaccessStream 实例?我今天才开始开发 C++ Metro 应用程序,所以可能是错误的,但我发现它过于复杂,因为洋葱皮太多。

【问题讨论】:

    标签: windows-8 windows-runtime winrt-xaml c++-cx imaging


    【解决方案1】:

    在 C# 中你会做类似的事情

    var storageFile = await Package.Current.InstalledLocation.GetFileAsync(relativePath.Replace('/', '\\'));
    var stream = await storageFile.OpenReadAsync();
    var wb = new WriteableBitmap(1, 1);
    wb.SetSource(stream);
    

    我认为在 C++/CX 中你会做这样的事情:

    #include <ppl.h>
    #include <ppltasks.h>
    
    ...
    
    Concurrency::task<Windows::Storage::StorageFile^> getFileTask
        (Package::Current->InstalledLocation->GetFileAsync(L"Assets\\MyImage.jpg"));
    
    auto getStreamTask = getFileTask.then(
        [] (Windows::Storage::StorageFile ^storageFile)
        {
            return storageFile->OpenReadAsync();
        });
    
    getStreamTask.then(
        [] (Windows::Storage::Streams::IRandomAccessStreamWithContentType^ stream)
        {
            auto wb = ref new Windows::UI::Xaml::Media::Imaging::WriteableBitmap(1, 1);
            wb->SetSource(stream);
        });
    

    【讨论】:

    • 感谢 Filip,它就像一个魅力。不过,我不得不做一点小改动。将 L"Assets\\MyImage.jpg" 更改为 L"MyImage.jpg",因为由于某种原因我得到了一个无效的参数异常。
    • 终于发现 WritableBitmap 的像素内容既不可读也不可写 :( 我可以得到一个 IBuffer 指针,它不提供对它的缓冲区的访问!无论如何,这是一个单独的问题。
    • @abix 在 C# 中,我使用 AsStream 方法将缓冲区转换为 I/O 流。它也必须在 C++ 中是可行的。检查 C# 示例here。
    • 我在另一个论坛中找到了一个解决方案,例如如何从 IBuffer 获取字节*... IUnknown* pUnk = reinterpret_cast(writableImage->PixelBuffer); IBufferByteAccess* pBufferByteAccess = nullptr; HRESULT hr = pUnk->QueryInterface(IID_PPV_ARGS(&pBufferByteAccess));字节*像素= nullptr; pBufferByteAccess->Buffer(&pixels);
    猜你喜欢
    • 2014-04-05
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2015-09-21
    相关资源
    最近更新 更多