2
votes

I'm making a Windows Phone 8.1 app (Windows Runtime, not Silverlight 8.1), and I need to create a WriteableBitmap from a Stream, but when I try to do so, I get this exception: "An exception of type 'System.Exception' occurred in mscorlib.ni.dll but was not handled in user code

Additional information: The component cannot be found. (Exception from HRESULT: 0x88982F50)"

I have tried a lot of things, but still no luck. My code is as follows:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var files = await KnownFolders.CameraRoll.GetFilesAsync();
    for(int i=0; i<files.Count; i++)
    {
        var fileStream = await files[i].OpenReadAsync();
        if(fileStream != null)
        {
             WriteableBitmap writeableBmp = await BitmapFactory.New(1, 1).FromStream(fileStream);
        }
    }
}

But this doesn't happen if I replace

var fileStream = await files[i].OpenReadAsync();

with, for example,

var fileStream = await files[0].OpenReadAsync();

Any ideas? Thank you.

1

1 Answers

1
votes

That's odd. I take it you have checked the "Pictures Library" capability in your appxmanifest file.

This code works for me:

public static async Task<WriteableBitmap> GetWritableBitmapFromStream(Stream stream)
{
    var decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream());
    var pixelData = await decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, new BitmapTransform(), ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.DoNotColorManage);
    var pixels = pixelData.DetachPixelData();

    var bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
    using (var bmpStream = bmp.PixelBuffer.AsStream())
    {
        bmpStream.Seek(0, SeekOrigin.Begin);
        await bmpStream.WriteAsync(pixels, 0, (int)bmpStream.Length);
    }
    return bmp;
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var files = await KnownFolders.CameraRoll.GetFilesAsync();
    foreach (var file in files)
    {
        // need "using System.IO" for this extension method
        using (var fileStream = await file.OpenStreamForReadAsync())
        {
            WriteableBitmap writeableBmp = await GetWritableBitmapFromStream(fileStream);
            // do something with writableBmp
        }
    }
}