猿问

从本地存储加载图片 > OutofmemoryException

当我想从内部存储加载图片时,有时会延迟,但有时会出现 OutOfMemmoryException。


var picList = System.Instance.GetFiles("/storage/emulated/0/DCIM/Camera", true); //Its a string list, include the files name



                var inc = 0;


                foreach (var item in picList)

                {


                    var byteArray = FileSystem.Instance.ReadFile("/storage/emulated/0/DCIM/Camera", item.Split('/').Last(), true);


                    var toPicture = ImageSource.FromStream(() => new MemoryStream(byteArray));


                    var image = new Image

                    {

                        ClassId = inc.ToString(),

                        Source = toPicture,

                        WidthRequest = 200,

                        HeightRequest = 200,

                    };

    `        }

    }

我想我需要处理它,但我不知道如何处理。


慕少森
浏览 205回答 2
2回答

明月笑刀无情

很可能您永远不会image.Dispose()在图像实例上调用方法,因此永远不会释放分配给图像的内存。此外,您应该考虑不加载所有文件,而是按需加载它们。

富国沪深

我认为您应该在循环外声明变量并重用它们,而不是在每次迭代时声明新变量:byte[] byteArray = null;MemoryStream toPicture = null;Image image = null;  foreach (var item in picList){    byteArray = FileSystem.Instance.ReadFile("/storage/emulated/0/DCIM/Camera", item.Split('/').Last(), true);    toPicture = ImageSource.FromStream(() => new MemoryStream(byteArray));    image = new Image    {        ClassId = inc.ToString(),        Source = toPicture,        WidthRequest = 200,        HeightRequest = 200,    };}
随时随地看视频慕课网APP
我要回答