【发布时间】:2016-09-16 18:16:46
【问题描述】:
我需要将BitmapImage 转换为byte[],以便我可以将这些数据存储在 SQLite 数据库中,然后执行相反的操作来加载它。
我的 XAML 有一个图像:
<Image x:Name="image" HorizontalAlignment="Left" Height="254" Margin="50,117,0,0" VerticalAlignment="Top" Width="244" Source="Assets/LockScreenLogo.png"/>
我的 C# 代码:
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
}
这不起作用。
异常信息:
“在 mscorlib.ni.dll 中发生了“System.ArgumentNullException”类型的异常,但未在用户代码中处理
附加信息:值不能为空。”
有人可以帮助我吗?
【问题讨论】:
标签: c# sqlite bitmap uwp data-conversion