Opening a File Into WriteableBitmap

Nathan Sokalski 4,111 Reputation points
2020-08-02T01:55:23.797+00:00

This is a question that I'm sure has been asked many times before, but I still have trouble finding the answer. I have a file (*.png) that I need to open as a WriteableBitmap. I have the Uri and am able to open it as a BitmapImage, but I cannot seem to create a WriteableBitmap from it. Can anybody help me here? Thanks.

Developer technologies | Universal Windows Platform (UWP)
{count} votes

2 answers

Sort by: Most helpful
  1. Daniele 1,996 Reputation points
    2020-08-02T07:57:25.143+00:00

    If you have the Uri then you can use RandomAccessStreamReference.CreateFromUri to create a stream (valid chemes are http, https, ms-appx, and ms-appdata, docs here), and read from the stream to create the WriteableBitmap.

    Code sample:

    private async Task<WriteableBitmap> UriToWriteableBitmap(Uri uri)  
    {  
        var randomAccessStreamReference = RandomAccessStreamReference.CreateFromUri(uri);  
        using (IRandomAccessStreamWithContentType stream = await randomAccessStreamReference.OpenReadAsync())  
        {  
            return await StreamToWriteableBitmap(stream);  
        }  
    }  
      
    private static async Task<WriteableBitmap> StreamToWriteableBitmap(IRandomAccessStream stream)  
    {  
        var decoder = await BitmapDecoder.CreateAsync(stream);  
        var writeableBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);  
        stream.Seek(0);  
        await writeableBitmap.SetSourceAsync(stream);  
        return writeableBitmap;  
    }  
    

    You can use method StreamToWriteableBitmap above with StorageFile too:

    using (IRandomAccessStreamWithContentType stream = await storageFile.OpenReadAsync())  
    {  
        WriteableBitmap streamToWriteableBitmap = await StreamToWriteableBitmap(stream);  
    }  
    

    Here below another implementation of method StreamToWriteableBitmap that uses SoftwareBitmap class

    private static async Task<WriteableBitmap> StreamToWriteableBitmap(IRandomAccessStream stream)  
    {  
        var decoder = await BitmapDecoder.CreateAsync(stream);  
        using (SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync())  
        {  
            var writeableBitmap = new WriteableBitmap(softwareBitmap.PixelWidth, softwareBitmap.PixelHeight);  
            softwareBitmap.CopyToBuffer(writeableBitmap.PixelBuffer);  
            return writeableBitmap;  
        }  
    }  
    
    1 person found this answer helpful.
    0 comments No comments

  2. Peter Fleischer (former MVP) 19,341 Reputation points
    2020-08-02T07:18:55.543+00:00

    Hi,
    try following demo:

    15041-x1.png
    14954-x1.png

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.