Fatal Error System out of Memory Memory Label : Texture

I’m trying to save a WebCamTexture every 10th frame into a file. Below is the code on how I’m doing it :

    _backgroundVideoTexture = null;
     var guiTexture = (WebCamTexture)_backgroundVideoObject.GetComponent<GUITexture>().texture;
	_backgroundVideoTexture = new Texture2D(guiTexture.width, guiTexture.height);
	_backgroundVideoTexture.SetPixels(guiTexture.GetPixels());
	_backgroundVideoTexture.Apply();
    Color[] clearPixels = new Color[guiTexture.width * guiTexture.height];
	for (int i = 0; i < clearPixels.Length; i++) {
		clearPixels  *= Color.clear;*
  •   }*
    

StartCoroutine(LogRequestImage(_backgroundVideoTexture));

  • _backgroundVideoTexture.SetPixels (clearPixels);*
    Here is the Courtine :
    IEnumerator LogRequestImage(Texture2D snap)
  • { *
  •   // request image*
    
  •   var requestSnap = snap.EncodeToPNG();*
    
  •   File.WriteAllBytes(_recordDataFolder + _fileName + "_image" + ".jpg", requestSnap);*
    
  •   yield return null;*
    
  • }*
    After writing about 200 images to disk it crashes with below error in Logcat :
    Could not allocate memory: System out of memory!
    Trying to allocate: 4915056B with 16 alignment. MemoryLabel: Texture
    Allocation happend at: Line:464 in
    Memory overview

[ ALLOC_DEFAULT ] used: 5719339B | peak: 9405782B | reserved: 5880535B
[ ALLOC_TEMP_JOB ] used: 0B | peak: 0B | reserved: 524288B
[ ALLOC_GAMEOBJECT ] used: 3802498B | peak: 3802498B | reserved: 3811181B
[ ALLOC_GFX ] used: 452355278B | peak: 452355278B | reserved: 452360199B
[ ALLOC_PROFILER ] used: 0B | peak: 0B | reserved: 0B
[ ALLOC_TEMP_THREAD ] used: 32768B | peak: 0B | reserved: 2785280B
As it is quite apparent from the code that _backgroundvidetexture is nullified in the beginning to clear out any memory allocated to it and then allocated new memory using new Texture2D(). This function is called every 10th frame with each frame allocating and deallocating memory. This, IMO, should not lead to any memory leak. I have also tried using a local variable approach hoping it will be garbage collected but the error is still the same. Below is the local variable approach :
var guiTexture = (WebCamTexture)_backgroundVideoObject.GetComponent().texture;

  •   var snap = new Texture2D (guiTexture.width, guiTexture.height);*
    
  •   snap.SetPixels (guiTexture.GetPixels ());*
    
  •   snap.Apply ();*
    
  •   StartCoroutine (LogRequestImage (snap));*
    

I’d really appreciate if someone can figure out what possibly could be the source of this error.

If you’re done with the Texture, you should destroy it (perhaps after getting the bytes).

use Destroy(snap);

var requestSnap = snap.EncodeToPNG();
Destroy(snap); // DESTROY HERE
File.WriteAllBytes(_recordDataFolder + _fileName + "_image" + ".jpg", requestSnap);
yield return null;