Image Capturing from camera getting tilt to left 90 degree in MAUI

Pratap Singh, Ayush 20 Reputation points
2023-11-30T17:18:22.6733333+00:00

We have Implemented Photo capturing and choose photo from gallery and we also put one condition that if image size is greater that 512 KB then resize the image. And whenever the image size getting more that limit it is tilting to left by 90 degree.

How I can resolve this?

        private async Task<string> ResizeImage(Stream sourceStream, FileStream localFileStream, string localFilePath)
        {
            try
            {
                IImage image;
                Stream downSizeStream;
                image = PlatformImage.FromStream(sourceStream);
                if (image != null)
                {
                    IImage newImage = image.Downsize(300, true);
                    downSizeStream = newImage.AsStream();
                    await downSizeStream.CopyToAsync(localFileStream);
                    return localFilePath;
                }
                return null;

            }catch(Exception ex) {
                return null;
                System.Diagnostics.Debug.WriteLine(ex.Message);

            }


        }
        ```

```csharp
        public async Task<string> TakePhotoAsync(string accNo)
        {

            if (MediaPicker.Default.IsCaptureSupported)
            {
                FileResult photo = await MediaPicker.Default.CapturePhotoAsync();

                if (photo != null)
                {
                    // save the file into local storage
                    string localFilePath = Path.Combine(FileSystem.CacheDirectory, string.Format("{0}.{1}", accNo, photo.FileName));
                    using Stream sourceStream = await photo.OpenReadAsync();
                    using FileStream localFileStream = File.OpenWrite(localFilePath);
                    var fileSize = sourceStream.Length;

                    if (fileSize > 524288) // Greater then 512 kb then do resize 
                    {

                        return await ResizeImage(sourceStream, localFileStream, localFilePath); ;
                    }
                    else
                    {
                        await sourceStream.CopyToAsync(localFileStream);
                        return localFilePath;
                    }
                }

            }
            return null;
        }
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,975 questions
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 36,951 Reputation points Microsoft Vendor
    2023-12-04T07:47:36.7966667+00:00

    Hello,

    You could use the following code to do both scaling and rotating on the native platform.

    For Android:

    Create the static helper class in Platforms/Android folder.

    public static class RImageHelper
    {
        public static byte[] RotateBitmap(byte[] imageData,int width, int height)
        {
    
            Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
            Matrix matrix = new Matrix();
            matrix.SetRotate(90);
            Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, width, height,false);
            Bitmap RotatedImage = Bitmap.CreateBitmap(resizedImage,0,0, resizedImage.Width, resizedImage.Height,matrix, true);
            using (MemoryStream ms = new MemoryStream())
            {
                RotatedImage.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
                return ms.ToArray();
            }
           
        }
    }
    

    For iOS:

    Create the static helper class in Platforms/IOS folder.

    public static class RImageHelper
    {
        public static byte[] RotateBitmap(byte[] imageData, int width, int height)
        {
            UIImage originalImage = ImageFromByteArray(imageData);
            UIImageOrientation orientation = originalImage.Orientation;
           
            //create a 24bit RGB image
            using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
                                                 width, height, 8,
                                                 4 * width, CGColorSpace.CreateDeviceRGB(),
                                                 CGImageAlphaInfo.PremultipliedFirst))
            {
    
                RectangleF imageRect = new RectangleF(0, 0, width, height);
    
                // draw the image
                context.DrawImage(imageRect, originalImage.CGImage);
                //rotated 90° counterclockwise from the orientation of its original pixel data.
                UIKit.UIImage resizedImage = UIKit.UIImage.FromImage(context.ToImage(), 0, UIImageOrientation.Left);
    
                // save the image as a jpeg
                return resizedImage.AsJPEG().ToArray();
            }
        }
    
        private static UIImage ImageFromByteArray(byte[] data)
        {
            if (data == null)
            {
                return null;
            }
    
            UIKit.UIImage image;
            try
            {
                image = new UIKit.UIImage(Foundation.NSData.FromArray(data));
            }
            catch (Exception e)
            {
                Console.WriteLine("Image load failed: " + e.Message);
                return null;
            }
            return image;
        }
    }
    

    Invoke the method in MAUI:

    byte[] imageData;
    if (fileSize > 524288) // Greater then 512 kb then do resize
    {
    
        using (MemoryStream ms = new MemoryStream())
        {
            sourceStream.CopyTo(ms);
            imageData = ms.ToArray();
        }
    #if ANDROID
        var image = RImageHelper.RotateBitmap(imageData, 300, 300);
    #elif IOS
        var image = RImageHelper.RotateBitmap(imageData, 300, 300);
    #endif
    }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful