1

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"/>
3
  • 2
    "but seems don't work" is a very vague error description. Please provide a minimal reproducible example that reproduces your problem (all error messages included verbatim). Commented Oct 6, 2016 at 12:40
  • 1
    sorry for the poor description, "but seems don't work" : the image just don't show. Before trigger the event, the image was shown correctly, after triggering the event, the image shows nothing. Commented Oct 6, 2016 at 14:05
  • 1
    Never used UWP asynchronous programming with C++, but I guess there should be something like create_task(image->SetSourceAsync(stream)).then([](void) { outputPic->Source = image; });. And similar for any other asynchronous calls like WriteAsync. Commented Oct 6, 2016 at 14:21

1 Answer 1

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

Screenshot

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.