1>最初方案:
用wpf的image控件循环显示图片,达到动画效果,其实就是在后台代码动态改变Image.Source的值,关键代码:
for (int i = ; i < ; i++)//六百张图片
{
BitmapImage bmImg = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + i.ToString() + ".png"));
bmImg.CacheOption = BitmapCacheOption.None;
vimage..Source=bmImg.Clone();
System.Threading.Thread.Sleep();//每秒25帧
}
由于Image.Source切换BitmapImage后,仍然抓着旧的bmImg不放,导致内存溢出.再多的内存也不够用.
在网上也找了大家说的方案都不行.只能寻找其他方案.
2>最终方案:
思路:a>先把所有要加载的图片转换成二进制数组,再把数组缓存到List中;
b>循环List,把二进制图片转换成MemoryStream;
c>把MemoryStream,通过ImageSourceConverter.ConvertFrom() as BitmapFrame,进行转换.
优点:先把图片缓存成二进制,这样可以释放对图片文件资源的占用,后面代码执行效率高;用通过MemoryStream生成的Source,用完就被释放了[暂时解释不了]!
核心代码:
imageSourceConverter = new ImageSourceConverter();
byList = new List<byte[]>();
for (int i = ; i < ; i++)
{
using (BinaryReader binReader = new BinaryReader(File.Open(AppDomain.CurrentDomain.BaseDirectory + i.ToString() + ".png", FileMode.Open)))
{
FileInfo fileInfo = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + i.ToString() + ".png");
//byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
//byList.Add(bytes); if ((long)int.MaxValue > fileInfo.Length)
{
byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);
byList.Add(bytes);
}
else
{
int leng = ;
byte[] bytes = new byte[fileInfo.Length];
for (long j = ; j < (fileInfo.Length / (long)leng + (long)); j++)
{
byte[] b = binReader.ReadBytes(leng);
if (b == null || b.Length < )
{
break;
}
for (long jj = j * leng; jj < (j + ) * leng; jj++)
{
bytes[jj] = b[jj % leng];
}
}
byList.Add(bytes);
}
}
}
// // //////////////
for (int i = 0; i < byList.Count; i++)
{
MemoryStream stream = new MemoryStream(byList[i]);
vimage.Source = imageSourceConverter.ConvertFrom(stream) as BitmapFrame;
System.Threading.Thread.Sleep(40);
}
真诚期待大家指导...