K.Chang
K.Chang

Reputation: 21

c++ byte array to bitmapimage

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"/>

Upvotes: 1

Views: 2212

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

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);
    });
}

Screenshot

Upvotes: 1

Related Questions