0

I need to convert a BitmapImage to byte[] so I can store this data in a SQLite database, and do the opposite to load it.

My XAML has an image:

<Image x:Name="image" HorizontalAlignment="Left" Height="254" Margin="50,117,0,0" VerticalAlignment="Top" Width="244" Source="Assets/LockScreenLogo.png"/>

My C# code:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        BitmapImage test = new BitmapImage();
        test = (BitmapImage)image.Source;
        image.Source = test;

        byte[] array = ImageToByte(test);
        Database.CreateDB();
        Database.InsertData(array);
    }



    #region convert
    public byte[] ImageToByte(BitmapImage image)
    {

        //WriteableBitmap wb;
        using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
        {
            image.SetSource(ms);

            WriteableBitmap wb = new WriteableBitmap(244, 254);
            wb.SetSource(ms);

            using (Stream stream = wb.PixelBuffer.AsStream())
            using (MemoryStream memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                return memoryStream.ToArray();
            }
        }
    }

    public BitmapImage ByteToImage(byte[] array)
    {
        BitmapImage image = new BitmapImage();
        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
        {
            stream.AsStreamForWrite().Write(array, 0, array.Length);
            stream.Seek(0);
            image.SetSource(stream);
        }
        return image;
    }
    #endregion

}

This is not working.

the exception message:

"An exception of type 'System.ArgumentNullException' occurred in mscorlib.ni.dll but was not handled in user code

Additional information: Value cannot be null."

Someone can help me?

Giorge Caique
  • 199
  • 1
  • 1
  • 16
  • Possible duplicate of [Convert a BitmapImage to byte array in UWP](http://stackoverflow.com/questions/36108056/convert-a-bitmapimage-to-byte-array-in-uwp) – Clemens Sep 17 '16 at 11:55

1 Answers1

0

Unfortunately that is impossible unless you have the undelaying source of the image (like the StorageItem or URL).

To get access to the Pixels (and make any processing afterwards) you need a WriteableBitmap object instead of a BitmapImage.

Graham
  • 7,431
  • 18
  • 59
  • 84
AlexDrenea
  • 7,981
  • 1
  • 32
  • 49