1>最初方案:
用wpf的image控件循環顯示圖片,達到動畫效果,其實就是在后台代碼動態改變Image.Source的值,關鍵代碼:
for (int i = 1; i < 601; 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(40);//每秒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 = 1; i < 601; 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 = 1024; byte[] bytes = new byte[fileInfo.Length]; for (long j = 0; j < (fileInfo.Length / (long)leng + (long)1); j++) { byte[] b = binReader.ReadBytes(leng); if (b == null || b.Length < 1) { break; } for (long jj = j * leng; jj < (j + 1) * 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);
}
真誠期待大家指導...