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.