![](/img/trans.png)
[英]OutOfMemory Exception in <BitmapImage>.SetSource()
[英]UWP BitmapImage SetSource from MemoryStream hangs
在我的UWP應用中,我將圖像以byte []的形式存儲在SQLite數據庫中。 然后,當我從數據庫檢索對象時,我將它們綁定到具有Image控件的GridView數據模板。 由於我無法將Image的Source直接綁定到數組,因此我在對象的類中創建了BitmapImage屬性以將Image控件綁定到:
public BitmapImage Icon
{
get
{
using (var stream = new MemoryStream(icon))
{
stream.Seek(0, SeekOrigin.Begin);
var img = new BitmapImage();
img.SetSource(stream.AsRandomAccessStream());
return img;
}
}
}
問題是,我的應用程序掛在img.SetSource行上。 經過一些試驗,我發現可以使用第二個MemoryStream克服此問題:
public BitmapImage Icon
{
get
{
using (var stream = new MemoryStream(icon))
{
stream.Seek(0, SeekOrigin.Begin);
var s2 = new MemoryStream();
stream.CopyTo(s2);
s2.Position = 0;
var img = new BitmapImage();
img.SetSource(s2.AsRandomAccessStream());
s2.Dispose();
return img;
}
}
}
由於某些原因,它不會掛起。 我想知道為什么? 以及如何正確處理這種情況? 謝謝!
我建議您在應用程序中顯示圖像之前使用IValueConverter界面。
class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null || !(value is byte[]))
return null;
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes((byte[])value);
writer.StoreAsync().GetResults();
}
var image = new BitmapImage();
image.SetSource(ms);
return image;
}
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
為什么不使用Base64? 將Base64圖像保存在sqlite數據庫列中,並將其輕松綁定到Image控件。
<Image Source="{Binding Path=imagedata}" Height="120" Width="120"></Image>
從sqlite db綁定到Gridview內部的圖像要容易得多。
我使用在轉換器中使用的擴展方法:
public static BitmapImage AsBitmapImage(this byte[] byteArray)
{
if (byteArray != null)
{
using (var stream = new InMemoryRandomAccessStream())
{
stream.WriteAsync(byteArray.AsBuffer()).GetResults();
// I made this one synchronous on the UI thread;
// this is not a best practice.
var image = new BitmapImage();
stream.Seek(0);
image.SetSource(stream);
return image;
}
}
return null;
}
在發現從RandomAccessStreams加載的圖像之前,我一直遇到問題。 它們在應用程序中的視覺效果很好,但在動態生成打印預覽時會掛起UI。
轉換效果很好,歡呼。
private BitmapImage ConvertImage(string str) {
byte[] imgData = Convert.FromBase64String(str);
using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
{
using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
{
writer.WriteBytes(imgData);
writer.StoreAsync.GetResults();
}
BitmapImage result = new BitmapImage();
result.SetSource(ms);
return result;
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.