public static Bitmap LoadAndResizeBitmap(this string fileName, int width, int height) { // First we get the the dimensions of the file on disk BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeFile(fileName, options); // Next we calculate the ratio that we need to resize the image by // in order to fit the requested dimensions. int outHeight = options.OutHeight; int outWidth = options.OutWidth; int inSampleSize = 1; if (outHeight > height || outWidth > width) { inSampleSize = outWidth > outHeight ? outHeight / height : outWidth / width; } // Now we will load the image and have BitmapFactory resize it for us. options.InSampleSize = inSampleSize; options.InJustDecodeBounds = false; Bitmap resizedBitmap = BitmapFactory.DecodeFile(fileName, options); // Images are being saved in landscape, so rotate them back to portrait if they were taken in portrait Matrix mtx = new Matrix(); Android.Media.ExifInterface exif = new Android.Media.ExifInterface(fileName); Android.Media.Orientation orientation = (Android.Media.Orientation)exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, (int)Android.Media.Orientation.Undefined); switch (orientation) { case Android.Media.Orientation.Rotate90: // portrait mtx.PreRotate(90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false); mtx.Dispose(); mtx = null; break; case Android.Media.Orientation.FlipHorizontal: // landscape break; default: mtx.PreRotate(90); resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false); mtx.Dispose(); mtx = null; break; } return(resizedBitmap); }
public void MyCropImage(Bitmap bitmap, Android.Net.Uri uri) { string path = ""; int rotation = 0; try { if (activity.HasAccess(Manifest.Permission.ReadExternalStorage, PermissionRequestCode.Storage, "Grant accesss to ensure correct image orientation")) { path = GetPathToImage(uri); } Android.Media.ExifInterface exif = new Android.Media.ExifInterface(path); Android.Media.Orientation orientation = (Android.Media.Orientation)exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, 0); switch (orientation) { case Android.Media.Orientation.Rotate90: rotation = 90; break; case Android.Media.Orientation.Rotate180: rotation = 180; break; case Android.Media.Orientation.Rotate270: rotation = 270; break; default: rotation = 0; break; } } catch (Exception ex) { ex.Log(); } using (bitmap) using (Matrix matrix = new Matrix()) { matrix.PreRotate(rotation); int width1 = bitmap.Width; int height1 = bitmap.Height; int diffX = 0, diffY = 0; if (width1 > height1) { diffX = (width1 - height1) / 2; width1 = height1; } else { diffY = (height1 - width1) / 2; height1 = width1; } croppedBitmap = Bitmap.CreateBitmap(bitmap, diffX, diffY, width1, height1, matrix, true); croppedBitmap = Bitmap.CreateScaledBitmap(croppedBitmap, 250, 250, true); imgView.SetImageBitmap(croppedBitmap); } }