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?