Last active
December 16, 2021 14:18
-
-
Save eclipsed4utoo/d5712e5fef0a9a2fcef9 to your computer and use it in GitHub Desktop.
Xamarin.Android Rotate and Resize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static System.IO.Stream ResizeAndRotate(string filePath, int maxWidth, int maxHeight, float jpegQuality) | |
{ | |
// loads just the dimensions of the file instead of the entire image | |
var options = new BitmapFactory.Options { InJustDecodeBounds = true }; | |
BitmapFactory.DecodeFile (filePath, options); | |
int outHeight = options.OutHeight; | |
int outWidth = options.OutWidth; | |
int inSampleSize = 1; | |
if (outHeight > maxHeight || outWidth > maxWidth) | |
{ | |
inSampleSize = (outWidth > outHeight) ? outWidth / maxWidth : outHeight / maxHeight; | |
} | |
options.InSampleSize = inSampleSize; | |
options.InJustDecodeBounds = false; | |
// decodes image file | |
var newBitmap = BitmapFactory.DecodeFile (filePath, options); | |
var matrix = new Matrix (); | |
// rotates the image if needed. | |
// Known Issue: HTC phones will report all pictures as landscape orientation. | |
ExifInterface exif = new ExifInterface (filePath); | |
var orientation = (Orientation)exif.GetAttributeInt (ExifInterface.TagOrientation, (int)Orientation.Undefined); | |
switch(orientation) | |
{ | |
case Orientation.Normal: | |
// landscape. Don't do anything | |
break; | |
case Orientation.Rotate180: | |
matrix.PreRotate (180); | |
break; | |
case Orientation.Rotate270: | |
matrix.PreRotate (270); | |
break; | |
default: | |
// handles portrait and other orientations that we may not need to handle. | |
matrix.PreRotate (90); | |
break; | |
} | |
newBitmap = Bitmap.CreateBitmap(newBitmap, 0, 0, newBitmap.Width, newBitmap.Height, matrix, false); | |
matrix.Dispose(); | |
matrix = null; | |
byte[] newImageData; | |
int quality = (int)(jpegQuality * 100); | |
using (var stream = new System.IO.MemoryStream()) | |
{ | |
newBitmap.Compress(Bitmap.CompressFormat.Jpeg, quality, stream); | |
newBitmap.Recycle (); | |
newBitmap.Dispose (); | |
newBitmap = null; | |
return stream; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment