需求:讀取高分辨率圖檔顯示到寬度為200的Image控件上
核心代碼:
private BitmapImage ReadImageFiletToBinary(string fileName)
{
using (var stream = new FileStream(fileName, FileMode.Open))
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
int streamLen = (int)stream.Length;
byte[] imageData = new byte[stream.Length];
stream.Read(imageData, 0, streamLen);
bitmapImage.StreamSource = new MemoryStream(imageData, 0, streamLen);
bitmapImage.DecodePixelWidth = 200; //設定解碼後圖像的寬度,圖像變小,解析變快
bitmapImage.EndInit();
return bitmapImage;
}
這樣占用的記憶體很低,原本直接讀取10幾張圖需要占用150M記憶體,現在隻需不到5M