Load a large BitmapImage asynchronously

|▌冷眼眸甩不掉的悲伤 提交于 2020-07-27 09:15:13

问题


I'm trying to load a very large image (about 16000x7000 pixel) into a Material, and I've tried to load it asynchronously. My first try was to create a task that loaded the BitmapImage and then use it into the material:

var bmp = await System.Threading.Tasks.Task.Run(() =>
{
    BitmapImage img = new BitmapImage(new Uri(path));
    ImageBrush brush = new ImageBrush(img);
    var material = new System.Windows.Media.Media3D.DiffuseMaterial(brush);
    material.Freeze();
    return material;
});
BackMaterial = bmp;

But what I've found is that the image it is not loaded and expanded into memory until the material is shown (it's the same if I use the ImageBrush directly).

I'm trying to avoid that because it freezes my UI, but I haven't found the right way to force the bitmap loadi and decode. If I add a WriteableBitmap the load of the picture is performed inside the Task, but then I'm doubling the amount of memory being used:

var bmp = await System.Threading.Tasks.Task.Run(() =>
{
    BitmapImage img = new BitmapImage(new Uri(path));
    WriteableBitmap wbmp = new WriteableBitmap(img);
    ImageBrush brush = new ImageBrush(wbmp);
    var material = new System.Windows.Media.Media3D.DiffuseMaterial(brush);
    material.Freeze();
    return material;
});
BackMaterial = bmp;

Is there any way to force the load without doubling it into memory. I also tried to load it with a decoder, but I'm also loading into memory twice:

var decoder = BitmapDecoder.Create(new Uri(path), BitmapCreateOptions.PreservePixelFormat,
     BitmapCacheOption.None);
var frame = decoder.Frames[0];
int stride = frame.PixelWidth * frame.Format.BitsPerPixel / 8;
byte[] lines = new byte[frame.PixelHeight * stride];
frame.CopyPixels(lines, stride, 0);
var img = BitmapImage.Create(
    frame.PixelWidth, frame.PixelHeight, frame.DpiX, frame.DpiY, frame.Format,
    frame.Palette, lines, stride);
frame = null;
lines = null;

Thanks!


回答1:


I'm not sure about this asynchronous scenario, but you would usually set BitmapCacheOption.OnLoad to force immediate caching to memory:

var bmp = await System.Threading.Tasks.Task.Run(() => 
{ 
    BitmapImage img = new BitmapImage(); 
    img.BeginInit(); 
    img.CacheOption = BitmapCacheOption.OnLoad; 
    img.UriSource = new Uri(path); 
    img.EndInit(); 
    ImageBrush brush = new ImageBrush(img); 
    ...
}


来源:https://stackoverflow.com/questions/12825233/load-a-large-bitmapimage-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!