title: Xamarin MediaPicker CapturePhotoAsync restarting the app after pressing "Ok" button and throwing silent error
body: <p>I have been experiencing an error while using the XamarinEssentials.MediaPicker CapturePhotoAsync() method. Some users of an application of mine have been going through silent crashes that restarts the app without logging anything to the appCenter right after accepting the picture that was taken. (video of the error attatched <a href="https://drive.google.com/file/d/1oCXHTNEOc-K_FXaUL2xhMym8LBJ0nijh/view?usp=sharing" rel="nofollow noreferrer">here</a> ). Note that this video was taken by a user that holds a Xiami Redmi Note 9S and I do not have access to this device. I could not manage to reproduce this error on any device that I have tested. Not in development Mode nor Release.</p>
  <p>Appearently it is some bug going inside MediaPicker code that consumes all the available RAM of the device, forcing it to restart.</p>
  <p>I have seen a lot of other reports on the internet but any of them would come up with a conclusion or a solution.</p>
  <p>Can someone help me fix this issue?</p>
  <p>Thanks in advance!</p>
  <p>Find Below the entire code envolved in capturing the picture and also post-processing it, envolving resizing the image, rotating it, saving it to gallery and also save a thumbnail.</p>
  <pre><code>public async Task TakePicture(object param)
      {
          var permissionsOk = await VerifyPermissions();
          if (!permissionsOk) return;
  
          try
          {
              var options = new MediaPickerOptions
              {
  
              };
              var photo = await MediaPicker.CapturePhotoAsync();
              await LoadPhotoAsync(photo);
              Console.WriteLine($&quot;CapturePhotoAsync COMPLETED: {PhotoPath}&quot;);
          }
          catch (FeatureNotSupportedException fnsEx)
          {
              // Feature is not supported on the device
              var properties = new Dictionary&lt;string, string&gt;
                  {
                      { &quot;Função:&quot;, &quot;TakePicture&quot; },
                      { &quot;Arquivo:&quot;, &quot;VisitDetailsRegistrationViewModel&quot;},
                      { &quot;Observação&quot;, &quot;FeatureNotSupportedException&quot;}
                  };
              Crashes.TrackError(fnsEx, properties);
          }
          catch (PermissionException pEx)
          {
              // Permissions not granted
              var properties = new Dictionary&lt;string, string&gt;
                  {
                      { &quot;Função:&quot;, &quot;TakePicture&quot; },
                      { &quot;Arquivo:&quot;, &quot;VisitDetailsRegistrationViewModel&quot;},
                      { &quot;Observação&quot;, &quot;PermissionException&quot;}
                  };
              Crashes.TrackError(pEx, properties);
          }
          catch (Exception ex)
          {
              var properties = new Dictionary&lt;string, string&gt;
                  {
                      { &quot;Função:&quot;, &quot;TakePicture&quot; },
                      { &quot;Arquivo:&quot;, &quot;VisitDetailsRegistrationViewModel&quot;},
                      { &quot;Observação&quot;, &quot;Exception&quot;}
                  };
              Crashes.TrackError(ex, properties);
          }
      }
  
      async Task LoadPhotoAsync(FileResult photo)
      {
          // canceled
          if (photo == null)
          {
              PhotoPath = null;
              return;
          }
  
          var meta = ImageMetadataReader.ReadMetadata(await photo.OpenReadAsync());
          var subIfd0Directory = meta.OfType&lt;ExifIfd0Directory&gt;().FirstOrDefault();
          var orientation = subIfd0Directory?.GetDescription(ExifDirectoryBase.TagOrientation);
          var rotationAngle = GetRotationAngle(orientation);
  
          // save the file into local storage
          var newFile = System.IO.Path.Combine(FileSystem.CacheDirectory, photo.FileName);
          using (var stream = await photo.OpenReadAsync())
          {
              var imageByteArray = ReadFully(stream);
              //var resizedImageByteArray = ResizeImage(imageByteArray, 2000, 2000, 92);
              var rotatedImageByteArray = RotateImage(imageByteArray, rotationAngle, 92);
              //var mediaService = DependencyService.Get&lt;IMediaService&gt;();
              //mediaService.SaveImageFromByte(rotatedImageByteArray, photo.FileName);
              using (MemoryStream ms = new MemoryStream(rotatedImageByteArray))
              {
                  using (var newStream = File.OpenWrite(newFile))
                  {
                      await ms.CopyToAsync(newStream);
                  }
              }
              using (MemoryStream ms2 = new MemoryStream(rotatedImageByteArray))
              {
                  try
                  {
                      await MediaGallery.SaveAsync(MediaFileType.Image, ms2, photo.FileName);
                  }
                  catch (Exception ex)
                  {
                      var properties = new Dictionary&lt;string, string&gt;
                      {
                          { &quot;Função:&quot;, &quot;LoadPhotoAsync&quot; },
                          { &quot;Arquivo:&quot;, &quot;VisitDetailsRegistrationViewModel&quot;},
                          { &quot;Observação&quot;, &quot;Exception&quot;}
                      };
                      Crashes.TrackError(ex, properties);
                  }
              }
          }
          PhotoPath = newFile;
  
          var thumbFile = System.IO.Path.Combine(FileSystem.CacheDirectory, &quot;Thumb-&quot;+photo.FileName);
          using (var stream = await photo.OpenReadAsync())
          {
              var thumbByteArray = ReadFully(stream);
              var resizedThumbByteArray = ResizeImage(thumbByteArray, 500, 500, 92);
              var rotatedThumbByteArray = RotateImage(resizedThumbByteArray, rotationAngle, 92);
              using (MemoryStream ms = new MemoryStream(rotatedThumbByteArray))
              {
                  using (var newStreamThumb = File.OpenWrite(thumbFile))
                      await ms.CopyToAsync(newStreamThumb);
              }
          }
          ThumbPath = thumbFile;
      }
  
      public int GetRotationAngle(string orientationText)
      {
          if (orientationText == null) return 90;
  
          if (orientationText.Contains(&quot;90&quot;)) return 90;
          else if (orientationText.Contains(&quot;180&quot;)) return 180;
          else if (orientationText.Contains(&quot;270&quot;)) return 270;
          else return 0;
      }
  
      public static byte[] ReadFully(Stream input)
      {
          byte[] buffer = new byte[16 * 1024];
          using (MemoryStream ms = new MemoryStream())
          {
              int read;
              while ((read = input.Read(buffer, 0, buffer.Length)) &gt; 0)
              {
                  ms.Write(buffer, 0, read);
              }
              return ms.ToArray();
          }
      }
  
      public static byte[] RotateImage(byte[] imageData, float degrees, int quality)
      {
          Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
  
          var matrix = new Matrix();
  
          matrix.PostRotate(degrees);
  
          Bitmap rotatedBitmap = Bitmap.CreateBitmap(originalImage, 0, 0, originalImage.Width, originalImage.Height, matrix, true);
  
          using (MemoryStream ms = new MemoryStream())
          {
              rotatedBitmap.Compress(Bitmap.CompressFormat.Jpeg, quality, ms);
              return ms.ToArray();
          }
      }
  
      public static byte[] ResizeImage(byte[] imageData, float width, float height, int quality)
      {
          // Load the bitmap
          Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
  
          float oldWidth = (float)originalImage.Width;
          float oldHeight = (float)originalImage.Height;
          float scaleFactor = 0f;
  
          if (oldWidth &gt; oldHeight)
          {
              scaleFactor = width / oldWidth;
          }
          else
          {
              scaleFactor = height / oldHeight;
          }
  
          float newHeight = oldHeight * scaleFactor;
          float newWidth = oldWidth * scaleFactor;
  
          Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)newWidth, (int)newHeight, false);
  
          using (MemoryStream ms = new MemoryStream())
          {
              resizedImage.Compress(Bitmap.CompressFormat.Jpeg, quality, ms);
              return ms.ToArray();
          }
      }
  </code></pre>