5

I have a Universal Windows application that hosts a main menu. I want a plugin architecture, where the menu items are added from class libraries.

But I can't seem to load images correctly. I can't get the ms-appx:/// working, and when I try to add the images as an embedded resource, it hangs:

var assembly = typeof(CookModule).GetTypeInfo().Assembly;
using (var imageStream = assembly.GetManifestResourceStream("My.Namespace.Folder.ImageName-100.png"))
using (var raStream = imageStream.AsRandomAccessStream())
{
    var bitmap = new BitmapImage();
    bitmap.SetSource(raStream); //<- Hangs here

I get no exceptions, errors in the output or anything. It just hangs there, and the app simply doesn't load the page.

I have also tried:

var bitmap = new BitmapImage(new Uri("/Folder/ImageName-100.png"));

I'm missing something similar to the WPF pack uri's where I can state which assembly to load the image from.

What is the correct (and working) way of adding a image resource to a Page from a class libary? (Or does anyone have a working example of ms-appx where the image is in a class library)

Troels Larsen
  • 4,462
  • 2
  • 34
  • 54

1 Answers1

8

I can reproduce this issue. Current workaround I used is copying the resource stream to .NET memory stream.

        var assembly = typeof(CookModule).GetTypeInfo().Assembly;

        using (var imageStream = assembly.GetManifestResourceStream("UWP.ClassLibrary.210644575939381015.jpg"))
        using (var memStream = new MemoryStream())
        {
            await imageStream.CopyToAsync(memStream);

            memStream.Position = 0;

            using (var raStream = memStream.AsRandomAccessStream())
            {
                var bitmap = new BitmapImage();
                bitmap.SetSource(raStream);

                display.Source = bitmap;
            }
        }
Jeffrey Chen
  • 4,650
  • 1
  • 18
  • 22
  • 1
    Yeah that definitely works. I don't really understand why though. Shouldn't a Stream be a Stream? Anyway, accepting this answer. It would've taken me quite a while to figure that one out! – Troels Larsen Oct 13 '15 at 20:07
  • At a guess, and stepping through the debug of it, it's because the GetManifestResourceStream() ends up returning an UnmanagedResourceStream. We're then copying that over into a managed MemoryStream that managed code can access. – Thought Apr 03 '17 at 16:46