需求:讀取高分辨率圖片顯示到寬度為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