Photos taken using MediaPicker.CapturePhotoAsync are rotated 90 degrees

Wei Wen 1,096 Reputation points
2021-10-12T19:56:42.487+00:00

This is the case for both Android and iOS. Because of this, I have to rotate the image. I did this on Android with this code:

[assembly:Xamarin.Forms.Dependency(typeof(ImageService))]
namespace KnowMobile.Droid.DependencyServices
{
public class ImageService : IImageUtil
{
private int GetImageRotation(string filePath)
{
try
{
ExifInterface ei = new ExifInterface(filePath);
Orientation orientation = (Orientation)ei.GetAttributeInt(ExifInterface.TagOrientation, (int)Orientation.Undefined);
switch (orientation)
{
case Orientation.Rotate90:
return 90;
case Orientation.Rotate180:
return 180;
case Orientation.Rotate270:
return 270;
default:
return 0;
}
}
catch (Exception ex)
{
return 0;
}
}

public byte[] RotateImage(System.IO.Stream imageStream, string filePath)
{
  int rotationDegrees = GetImageRotation(filePath);
  byte[] byteArray = new byte[imageStream.Length];
  try
  {
    imageStream.Read(byteArray, 0, (int)imageStream.Length);

    Bitmap originalImage = BitmapFactory.DecodeByteArray(byteArray, 0, byteArray.Length);
    Matrix matrix = new Matrix();
    matrix.PostRotate((float)rotationDegrees);

    Bitmap rotatedBitmap = Bitmap.CreateBitmap(originalImage, 0, 0, originalImage.Width,
        originalImage.Height, matrix, true);

    using (MemoryStream ms = new MemoryStream())
    {
      rotatedBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
      return ms.ToArray();
    }
  }
  catch (Exception ex)
  {
    return byteArray;
  }
}

}
}

I hope to be able to achieve the same result on iOS, if there is no way to adjust the photo orientation when using MediaPicker.CapturePhotoAsync. Any help is greatly appreciated!

A little background info for this strange behavior: Because my app only allows portrait mode, all pictures taken have larger height than width. So when rendered, they all lie on their heights. My Image's width and height are set to have a slightly larger width. But since I set its Aspect to be AspectFit, that shouldn't be the reason to change its orientation.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,296 questions
{count} votes