【发布时间】:2016-06-20 07:17:42
【问题描述】:
两天以来,我尝试在 WPF 应用程序中管理我的图像,但出现错误和错误错误,...
图像显示在 System.Windows.Control.Image 中。 出于这个原因,我尝试使用变量 BitMapImage。
现在出现错误:“无法访问关闭流”,我找不到解决方案。
我为转换创建了两个函数:
public static BitmapImage ConvertToBitMapImage(byte[] bytes)
{
if (bytes == null || bytes.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(bytes))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
//image.Freeze();
return image;
}
public static byte[] ImageToByte(BitmapImage imageSource)
{
Stream stream = imageSource.StreamSource;
Byte[] buffer = null;
if (stream != null && stream.Length > 0)
{
using (BinaryReader br = new BinaryReader(stream))
{
buffer = br.ReadBytes((Int32)stream.Length);
}
}
return buffer;
}
在我的对象中我有一个属性:
public BitmapImage MiniatureApp
{
get
{
if (IMAGES != null)
_MiniatureApp = Tools.BinaryImageConverter.ConvertToBitMapImage(IMAGES.IMAGE);
return _MiniatureApp;
}
set
{
if (this.IMAGES != null)
this.IMAGES.IMAGE = Tools.BinaryImageConverter.ImageToByte((BitmapImage)value);
else
{
IMAGES img = new IMAGES();
img.NOM = "";
img.IMAGE = Tools.BinaryImageConverter.ImageToByte((BitmapImage)value);
this.IMAGES = img;
}
NotifyPropertyChanged();
}
}
我主要是这样做的:
FileStream fs = new FileStream(pathImage, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
VMAppareil.VMApp.CurrentAppareil.MiniatureApp = Tools.BinaryImageConverter.ConvertToBitMapImage(data);
是否有解决我的问题的方法或最好的方法?
戈贝莱特。
【问题讨论】:
-
您的 ImageToByte 方法不正确,因为当您尝试访问 StreamSource 时它已关闭。这就是 BitmapCacheOption.OnLoad 所做的。这个答案解释了如何将 BitmapImage 保存到字节数组:stackoverflow.com/a/6597746/5574010
-
有什么理由将图像存储为字节数组(在 IMAGES.IMAGE 中)?
标签: c# arrays wpf byte bitmapimage