Zen Christophe
Zen Christophe

Reputation: 141

How to convert BitmapImage to WriteableBitmap in Universal application for windows 10?

I am implementing a Universal Windows Application on Windows 10 using MVVM. I have a file picker allowing me to choose an image. This image is displayed in an Image Control. The source of the Image Control is bound to a property in my view model. This property is a byte array. I need a converter to convert the BitmapImage in a Byte Array. I have read lots of things but can't found something working. I have found interesting stuff on https://writeablebitmapex.codeplex.com/ but if i want to use this package i need a WriteableBitmap and not a BitmapImage. Thank you in advance for your help.

Upvotes: 2

Views: 3393

Answers (1)

Igor Ralic
Igor Ralic

Reputation: 15006

You can load the image to a WriteableBitmap object straight from the file.

var filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".jpg");
var result = await filePicker.PickSingleFileAsync();

if (result != null)
{
    using (IRandomAccessStream stream = await result.OpenAsync(FileAccessMode.Read))
    {
        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
        WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
        bmp.SetSource(stream);

        // show the image in the UI if you want.
        MyImage.Source = bmp;
    }
}

This way you have the WriteableBitmap and you can use the WriteableBitmapEx library.

Upvotes: 5

Related Questions