WPF 解决Image控件读取高分辨率图片并缩放占用内存过大

需求:读取高分辨率图片显示到宽度为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

posted @ 2021-08-25 10:31  奇迹之耀  阅读(951)  评论(0编辑  收藏  举报