OutOfMemoryError when loading image

I have a simple page that displays an image. Source is URL

var img = new Image (); var source = new UriImageSource { Uri = new Uri (string.Format ("http://xxxx.com/imagem/?{0}", url)), CachingEnabled = false }; img .Source = source; 

but when I access this page (), for the fourth time or fifth, I get this error

 java.lang.OutOfMemoryError at android.graphics.Bitmap.nativeCreate(Native Method) at android.graphics.Bitmap.createBitmap(Bitmap.java:928) at android.graphics.Bitmap.createBitmap(Bitmap.java:901) at android.graphics.Bitmap.createBitmap(Bitmap.java:868) at md5530bd51e982e6e7b340b73e88efe666e.ButtonDrawable.n_draw(Native Method) at 340b73e88efe666e.ButtonDrawable.draw(ButtonDrawable.java:49) at android.view.View.draw(View.java:15235) at android.view.View.getDisplayList(View.java:14141)..... 
+5
source share
3 answers

We faced a very similar question. Appears Xamarin has released some recommendations on this , but it is not very similar to Xamarin Forms. Basically, before setting an image source, you need to decide whether to reduce it and do it manually. This will most likely require a Custom Renderer.

It seems that something for Xamarin Forms should do for us, but sometimes you have to perceive the bad with the good, I suppose.

The Xamarin forum on this issue is discussed here .

Update: I just noticed that you said that this only happens after 4 or 5 times when the page loads. We created a workaround on the page that solved the problem. Basically, you should set the image source back to null and force garbage collection when the page disappears. Like this:

 protected override void OnDisappearing () { base.OnDisappearing (); img.Source = null; GC.Collect (); } 
+4
source

I'm not that Xamarin.Forms expert, but on Xamarin.Android and Xamarin.iOS this is a very good behavior to use around this code or to delete an image (and its source). The reason for this is that the GC GC might think that the object is very small, so it does not need to free it immediately and holds the link, while the underlying instance that is at the base has a large number of MB.

+1
source

Manually resizing the image (via GIMP or some other image editor) seems to have helped. As others have noted, using garbage collector in OnDisappearing can also help.

0
source

All Articles