c++ byte array to bitmapimage

亡梦爱人 提交于 2019-12-12 02:46:29

问题


This is my first question on stackoverflow. I'm new to UWP programming, and due to some reason I need to do it in C++. Now I'm trying to solve this problem: I've got a byte array of images and want to show them in the UI. The following code is what I've tried but seems don't work. Here is C++ code:

BYTE input[160000] = ...;
InMemoryRandomAccessStream ^stream = ref new InMemoryRandomAccessStream();
DataWriter ^writer = ref new DataWriter();
writer->WriteBytes(Platform::ArrayReference<BYTE>(input, sizeof(input)));
stream->WriteAsync(writer->DetachBuffer());
stream->Seek(0);
BitmapImage ^image = ref new BitmapImage();
image->SetSourceAsync(stream);
outputPic->Source = image;

Here is xaml code:

<Image x:Name="outputPic" Source="Assets/Gray.png" Width="420" Stretch="Uniform" Height="420"/>

回答1:


Here's an example:

MainPage.xaml (excerpt)

<Image x:Name="image"/>

MainPage.xaml.cpp (excerpt)

#include <fstream>
#include <vector>
#include <iterator>

MainPage::MainPage()
{
    InitializeComponent();

    std::ifstream input("Assets\\StoreLogo.png", std::ios::binary);
    std::vector<char> data((std::istreambuf_iterator<char>(input)), (std::istreambuf_iterator<char>()));

    // I just obtained a pointer to the image data through data.data()

    auto bitmapImage = ref new BitmapImage();
    image->Source = bitmapImage;

    auto stream = ref new InMemoryRandomAccessStream();
    auto writer = ref new DataWriter(stream->GetOutputStreamAt(0));

    writer->WriteBytes(ArrayReference<unsigned char>((unsigned char*)data.data(), data.size()));

    create_task(writer->StoreAsync()).then([=](unsigned bytesStored)
    {
        return bitmapImage->SetSourceAsync(stream);
    });
}



来源:https://stackoverflow.com/questions/39896244/c-byte-array-to-bitmapimage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!