Beispiel #1
0
        private static Mat GetImageFromTask(Task <MediaFile> task, int maxWidth, int maxHeight)
        {
            MediaFile file = GetResultFromTask(task);

            if (file == null)
            {
                return(null);
            }

            int rotation = 0;

            Android.Media.ExifInterface exif = new Android.Media.ExifInterface(file.Path);
            int orientation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, int.MinValue);

            switch (orientation)
            {
            case (int)Android.Media.Orientation.Rotate270:
                rotation = 270;
                break;

            case (int)Android.Media.Orientation.Rotate180:
                rotation = 180;
                break;

            case (int)Android.Media.Orientation.Rotate90:
                rotation = 90;
                break;
            }

            using (Bitmap bmp = BitmapFactory.DecodeFile(file.Path))
            {
                if (bmp.Width <= maxWidth && bmp.Height <= maxHeight && rotation == 0)
                {
                    Mat m = new Mat();
                    m.SetBitmap(bmp);
                    return(m);
                }
                else
                {
                    using (Matrix matrix = new Matrix())
                    {
                        if (bmp.Width > maxWidth || bmp.Height > maxHeight)
                        {
                            double scale = Math.Min((double)maxWidth / bmp.Width, (double)maxHeight / bmp.Height);
                            matrix.PostScale((float)scale, (float)scale);
                        }
                        if (rotation != 0)
                        {
                            matrix.PostRotate(rotation);
                        }

                        using (Bitmap scaled = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true))
                        {
                            return(scaled.ToMat());
                        }
                    }
                }
            }
        }
Beispiel #2
0
        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);
        }
Beispiel #3
0
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            ContentResolver cr = context_.ContentResolver;

            /** 画像をファイルパスから検索 */


            BitmapFactory.Options options = new BitmapFactory.Options();
            options.InJustDecodeBounds = true;
            var    bitmap       = BitmapFactory.DecodeFile(image_[position]);
            int    imageHeight  = bitmap.Height;
            int    imageWidth   = bitmap.Width;
            String imageType    = options.OutMimeType;
            int    inSampleSize = 1;

            if (imageHeight > 320 || imageWidth > 240)
            {
                int halfHeight = imageHeight / 2;
                int halfWidth  = imageWidth / 2;

                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((halfHeight / inSampleSize) >= 320 &&
                       (halfWidth / inSampleSize) >= 240)
                {
                    inSampleSize *= 2;
                }
            }
            options.InSampleSize       = inSampleSize;
            options.InJustDecodeBounds = false;
            Android.Media.ExifInterface exif = new Android.Media.ExifInterface(image_[position]);
            //var orientation = int.Parse(exif.GetAttribute(Android.Media.ExifInterface.TagOrientation));
            var thumbnail = BitmapFactory.DecodeFile(image_[position], options);

            Android.Graphics.Matrix mat = new Android.Graphics.Matrix();


            if (thumbnail.Width > thumbnail.Height)
            {
                mat.SetRotate(90, thumbnail.Width / 2, thumbnail.Height / 2);
                mat.PreScale(320.0f / thumbnail.Width, 240.0f / thumbnail.Height);
            }
            else
            {
                mat.PreScale(240.0f / thumbnail.Width, 320.0f / thumbnail.Height);
            }
            thumbnail = Android.Graphics.Bitmap.CreateBitmap(thumbnail, 0, 0, thumbnail.Width, thumbnail.Height, mat, true);
            ((CameraViewHolder)holder).image_.SetImageBitmap(thumbnail);

            holder.ItemView.Click -= ItemView_Click;
            holder.ItemView.Click += ItemView_Click;
        }
        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);
                }
        }
Beispiel #5
0
        public bool ReadFile(String fileName, Mat mat, CvEnum.ImreadModes loadType)
        {
            try
            {
                int rotation = 0;
                Android.Media.ExifInterface exif = new Android.Media.ExifInterface(fileName);
                int orientation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, int.MinValue);
                switch (orientation)
                {
                case (int)Android.Media.Orientation.Rotate270:
                    rotation = 270;
                    break;

                case (int)Android.Media.Orientation.Rotate180:
                    rotation = 180;
                    break;

                case (int)Android.Media.Orientation.Rotate90:
                    rotation = 90;
                    break;
                }

                using (Android.Graphics.Bitmap bmp = Android.Graphics.BitmapFactory.DecodeFile(fileName))
                {
                    if (rotation == 0)
                    {
                        bmp.ToMat(mat);
                    }
                    else
                    {
                        Android.Graphics.Matrix matrix = new Android.Graphics.Matrix();
                        matrix.PostRotate(rotation);
                        using (Android.Graphics.Bitmap rotated = Android.Graphics.Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true))
                        {
                            //manually disposed sooner such that memory is released.
                            bmp.Dispose();
                            rotated.ToMat(mat);
                        }
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                //throw;
                return(false);
            }
        }
Beispiel #6
0
        private static Matrix GetOrientation(ExifInterface exifInterface)
        {
            var orientation = (Orientation)exifInterface.GetAttributeInt(ExifInterface.TagOrientation, (int)Orientation.Undefined);

            var matrix = new Matrix();

            switch (orientation)
            {
            case Orientation.Normal:
                break;

            case Orientation.FlipHorizontal:
                matrix.SetScale(-1, 1);
                break;

            case Orientation.Rotate180:
                matrix.SetRotate(180);
                break;

            case Orientation.FlipVertical:
                matrix.SetRotate(180);
                matrix.PostScale(-1, 1);
                break;

            case Orientation.Transpose:
                matrix.SetRotate(90);
                matrix.PostScale(-1, 1);
                break;

            case Orientation.Rotate90:
                matrix.SetRotate(90);
                break;

            case Orientation.Transverse:
                matrix.SetRotate(-90);
                matrix.PostScale(-1, 1);
                break;

            case Orientation.Rotate270:
                matrix.SetRotate(-90);
                break;

            case Orientation.Undefined:
                _logger.LogDebug("Undefined photo orientation");
                break;
            }

            return(matrix);
        }
Beispiel #7
0
        public static async Task <MemoryStream> RotatePhotoAsync(
            this Uri uri,
            ContentResolver contentResolver,
            int width,
            int height)
        {
            ExifInterface exifInterface = null;

            try
            {
                using (var stream = contentResolver.OpenInputStream(uri))
                {
                    if ((int)Build.VERSION.SdkInt > 23)
                    {
                        exifInterface = new ExifInterface(stream);
                    }
                    else
                    {
                        exifInterface = new ExifInterface(uri.Path);
                    }
                }

                using (var matrix = GetOrientation(exifInterface))
                    using (var bitmap = ImageUtils.FromUri(contentResolver, uri, height, width))
                    {
                        if (matrix.IsIdentity)
                        {
                            return(await bitmap.CompressAsync());
                        }

                        using (var rotatedBitmap = RotateBitmap(bitmap, matrix))
                        {
                            return(await rotatedBitmap.CompressAsync());
                        }
                    }
            }
            catch (Exception e)
            {
                _logger.LogError("Photo rotation error has occurred", e);
                return(null);
            }
            finally
            {
                exifInterface?.Dispose();
            }
        }
Beispiel #8
0
        private Bitmap ExifRotateBitmap(ContentResolver contentResolver, Uri uri, Bitmap bitmap)
        {
            if (bitmap == null)
            {
                return(null);
            }

            var exif              = new Android.Media.ExifInterface(GetRealPathFromUri(contentResolver, uri));
            var rotation          = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, (Int32)Android.Media.Orientation.Normal);
            var rotationInDegrees = ExifToDegrees(rotation);

            if (rotationInDegrees == 0)
            {
                return(bitmap);
            }

            using (var matrix = new Matrix())
            {
                matrix.PreRotate(rotationInDegrees);
                return(Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true));
            }
        }
Beispiel #9
0
        public static int GetRotation(string filePath)
        {
            using var ei = new Android.Media.ExifInterface(filePath);
            var orientation = (Android.Media.Orientation)ei.GetAttributeInt(
                tag: Android.Media.ExifInterface.TagOrientation,
                defaultValue: (int)Android.Media.Orientation.Normal);

            switch (orientation)
            {
            case Android.Media.Orientation.Rotate90:
                return(90);

            case Android.Media.Orientation.Rotate180:
                return(180);

            case Android.Media.Orientation.Rotate270:
                return(270);

            default:
                return(0);
            }
        }
Beispiel #10
0
        public static Bitmap GetResizedBitmap(Bitmap bm, int orientation)
        {
            int   width  = bm.Width;
            int   height = bm.Height;
            float scaleWidth;
            float scaleHeight;
            float getWidthPer  = 0;
            float getHeightPer = 0;

            if (width > 3000 && height > 3000)
            {
                getWidthPer  = ((width * 21) / 100);
                getHeightPer = ((height * 9) / 100);
            }
            else if (width > 2000 && height > 2000)
            {
                getWidthPer  = ((width * 22) / 100);
                getHeightPer = ((height * 22) / 100);
            }
            else if (width > 1500 && height > 2000)
            {
                getWidthPer  = ((width * 33) / 100);
                getHeightPer = ((height * 33) / 100);
            }
            else if (width < 500 && height < 500)
            {
                getWidthPer  = 250;
                getHeightPer = 350;
            }
            else
            {
                getWidthPer  = ((width * 33) / 100);
                getHeightPer = ((height * 33) / 100);

                if (getWidthPer > 700)
                {
                    getWidthPer = ((width * 28) / 100);
                }

                if (getHeightPer > 600)
                {
                    getHeightPer = ((height * 28) / 100);
                }
            }

            scaleWidth  = ((float)getWidthPer) / width;
            scaleHeight = ((float)getHeightPer) / height;

            // CREATE A MATRIX FOR THE MANIPULATION.

            Matrix matrix = new Matrix();

            int rotate = 0;

            Android.Media.ExifInterface exif = new Android.Media.ExifInterface(Helpers.Constants.imgFilePath);
            var imgorientation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, -1);

            switch (imgorientation)
            {
            case (int)Android.Media.Orientation.Rotate270:
                rotate = 270;
                i      = 270;
                break;

            case (int)Android.Media.Orientation.Rotate180:
                rotate = 180;
                i      = 180;
                break;

            case (int)Android.Media.Orientation.Rotate90:
                rotate = 90;
                i      = 90;
                break;
            }
            matrix.PostRotate(rotate);
            // RESIZE THE BIT MAP
            matrix.PostScale(scaleWidth, scaleHeight);


            //width = (int)getWidthPer;
            //height = (int)getHeightPer;
            // RECREATE THE NEW BITMAP
            Bitmap resizedBitmap = Bitmap.CreateBitmap(bm, 0, 0, width, height, matrix, true);

            return(resizedBitmap);
        }
Beispiel #11
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if (requestCode == 88 && resultCode == Result.Ok)
            {
                imageUri = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri);
                imageView.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == CAMERA_REQUEST && resultCode == Result.Ok)
            {
                imageUri = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri);
                imageView.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 188 && resultCode == Result.Ok)
            {
                imageUri1 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri1));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri1);
                i1.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 189 && resultCode == Result.Ok)
            {
                imageUri1 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri1));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri1);
                i1.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 288 && resultCode == Result.Ok)
            {
                imageUri2 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri2));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri2);
                i2.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 289 && resultCode == Result.Ok)
            {
                imageUri2 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri2));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri2);
                i2.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 388 && resultCode == Result.Ok)
            {
                imageUri3 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri3));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri3);
                i3.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 389 && resultCode == Result.Ok)
            {
                imageUri3 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri3));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri3);
                i3.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 488 && resultCode == Result.Ok)
            {
                imageUri4 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri4));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri4);
                i4.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 489 && resultCode == Result.Ok)
            {
                imageUri4 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri4));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri4);
                i4.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 588 && resultCode == Result.Ok)
            {
                imageUri5 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri5));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri5);
                i5.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 589 && resultCode == Result.Ok)
            {
                imageUri5 = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUri5));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri5);
                i5.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 688 && resultCode == Result.Ok)
            {
                imageUris = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUris));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUris);
                iss.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 689 && resultCode == Result.Ok)
            {
                imageUris = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUris));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUris);
                iss.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 788 && resultCode == Result.Ok)
            {
                imageUril = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUril));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUril);
                il.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
            if (requestCode == 789 && resultCode == Result.Ok)
            {
                imageUril = data.Data;
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(Modules.ImagesHelp.GetPathToImage(this, imageUril));
                int degree = Java.Lang.Integer.ParseInt(exifInterface.GetAttribute(Android.Media.ExifInterface.TagOrientation));
                b = Android.Provider.MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUril);
                il.SetImageBitmap(Modules.ImagesHelp.rotateBitmap(b, degree));
            }
        }
        private Bitmap ExifRotateBitmap(ContentResolver contentResolver, Uri uri, Bitmap bitmap)
        {
            if (bitmap == null)
                return null;

            var exif = new Android.Media.ExifInterface(GetRealPathFromUri(contentResolver, uri));
            var rotation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, (Int32)Android.Media.Orientation.Normal);
            var rotationInDegrees = ExifToDegrees(rotation);
            if (rotationInDegrees == 0)
                return bitmap;

            using (var matrix = new Matrix())
            {
                matrix.PreRotate(rotationInDegrees);
                return Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);
            }
        }
        /// <summary>
        /// Rotate via EXIF information
        /// </summary>
        /// <param name="photoPath"></param>
        /// <returns></returns>
        public byte[] RotateImage(string photoPath)
        {
            Android.Graphics.BitmapFactory.Options options = new Android.Graphics.BitmapFactory.Options();
            options.InPreferredConfig = Android.Graphics.Bitmap.Config.Argb8888;
            Android.Graphics.Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeFile(photoPath, options);

            try
            {
                Android.Media.ExifInterface exifInterface = new Android.Media.ExifInterface(photoPath);
                int orientation = exifInterface.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, (int)Android.Media.Orientation.Normal);

                int rotate = 0;

                switch (orientation)
                {
                case (int)Android.Media.Orientation.Normal:
                    rotate = 0;
                    break;

                case (int)Android.Media.Orientation.Rotate90:
                    rotate = 90;
                    break;

                case (int)Android.Media.Orientation.Rotate270:
                    rotate = 270;
                    break;

                case (int)Android.Media.Orientation.Rotate180:
                    rotate = 180;
                    break;

                default:
                    rotate = 0;
                    break;
                }

                using (var ms = new System.IO.MemoryStream())
                {
                    Android.Graphics.Bitmap croppedBitmap = null;

                    Android.Graphics.Matrix mtx = new Android.Graphics.Matrix();
                    mtx.PreRotate(rotate);

                    if (bitmap.Width >= bitmap.Height)
                    {
                        croppedBitmap = Android.Graphics.Bitmap.CreateBitmap(
                            bitmap,
                            bitmap.Width / 2 - bitmap.Height / 2,
                            0,
                            bitmap.Height,
                            bitmap.Height,
                            mtx,
                            false);
                    }
                    else
                    {
                        croppedBitmap = Android.Graphics.Bitmap.CreateBitmap(
                            bitmap,
                            0,
                            bitmap.Height / 2 - bitmap.Width / 2,
                            bitmap.Width,
                            bitmap.Width,
                            mtx,
                            false);
                    }

                    croppedBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 100, ms);

                    croppedBitmap.Recycle();
                    croppedBitmap.Dispose();
                    croppedBitmap = null;

                    mtx.Dispose();
                    mtx = null;

                    bitmap.Recycle();
                    bitmap.Dispose();
                    bitmap = null;

                    return(ms.ToArray());
                }
            }
            catch
            {
                // <!-- Fail out -->
            }

            return(null);
        }
Beispiel #14
0
        public static Bitmap LoadFromStorage(string url, double width, double height)
        {
            var options = new BitmapFactory.Options {
                InJustDecodeBounds = true,
            };
            double optionsWidth, optionsHeight;
            var    fetchPath = url;

            if (iApp.Encryption.Required)
            {
                try
                {
                    var bytes = iApp.File.Read(fetchPath);
                    fetchPath = iApp.Factory.TempPath.AppendPath(url.GetHashCode() + System.IO.Path.GetExtension(url));
                    iApp.File.Save(fetchPath, bytes, EncryptionMode.NoEncryption);
                }
                catch (CryptographicException e)
                {
                    iApp.Log.Warn("Failed to decrypt file: {0}", e, url);
                }
            }

            using (BitmapFactory.DecodeFile(fetchPath, options))
            {
                optionsWidth  = options.OutWidth;
                optionsHeight = options.OutHeight;
                if (optionsWidth < 1 || optionsHeight < 1)
                {
                    Device.Log.Error("Failed to read image from {0}", url);
                    return(null);
                }
            }

            options = new BitmapFactory.Options
            {
                InMutable       = true,
                InTargetDensity = 1,
            };

            //allow 5% margin of error before using resize algorithm
            if (width > 0 && optionsWidth > width * 1.05 && height > 0 && optionsHeight > height * 1.05)
            {
                options.InDensity = (int)Math.Ceiling(Math.Max(Math.Max(1, optionsWidth / width), optionsHeight / height));
            }

            var matrix = new Matrix();

            if (fetchPath.EndsWith(".jpg") || fetchPath.EndsWith(".jpeg"))
            {
                var exif        = new Android.Media.ExifInterface(fetchPath);
                var orientation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, 1);
                switch (orientation)
                {
                case 6:
                    matrix.PostRotate(90);
                    break;

                case 3:
                    matrix.PostRotate(180);
                    break;

                case 8:
                    matrix.PostRotate(270);
                    break;
                }
            }

            Bitmap retval;

            try
            {
                using (var bit = BitmapFactory.DecodeFile(fetchPath, options))
                {
                    if (bit == null)
                    {
                        Device.Log.Error("Failed to read image from {0}", url);
                        return(null);
                    }
                    retval = Bitmap.CreateBitmap(bit, 0, 0, bit.Width, bit.Height, matrix, true);
                    bit.Recycle();
                }
            }
            catch (Exception e)
            {
                Device.Log.Error("Failed to read [{0}] image to [{1}]", e, new UI.Size(optionsWidth, optionsHeight), new UI.Size(width, height));
                return(null);
            }
            finally
            {
                if (fetchPath != url)
                {
                    iApp.File.Delete(fetchPath);
                }
            }

            return(retval);
        }
Beispiel #15
0
        public static async Task <MemoryStream> RotatePhotoAsync(
            this byte[] imageData,
            string tempDirectory,
            int requiredWidth,
            int requiredHeight)
        {
            ExifInterface exifInterface = null;
            var           memoryStream  = new MemoryStream(imageData);

            try
            {
                if ((int)Build.VERSION.SdkInt > 23)
                {
                    exifInterface = new ExifInterface(memoryStream);
                }
                else
                {
                    var file = await SavePhotoToDiskAsync(imageData, tempDirectory).ConfigureAwait(false);

                    if (file == null)
                    {
                        return(memoryStream);
                    }

                    exifInterface = new ExifInterface(file.CanonicalPath);

                    DeletePhotoFromDisk(file);
                }

                using (var options = new BitmapFactory.Options())
                    using (var matrix = GetOrientation(exifInterface))
                    {
                        if (matrix.IsIdentity)
                        {
                            memoryStream.Position = 0;
                            return(memoryStream);
                        }

                        options.InJustDecodeBounds = true;
                        options.InPreferredConfig  = Bitmap.Config.Rgb565;
                        memoryStream.Position      = 0;

                        await BitmapFactory.DecodeStreamAsync(memoryStream, null, options).ConfigureAwait(false);

                        var inSampleSize = GetInSampleSize(options, requiredWidth, requiredHeight);

                        options.InJustDecodeBounds = false;
                        options.InSampleSize       = inSampleSize;
                        memoryStream.Position      = 0;

                        using (var bitmap = await BitmapFactory.DecodeStreamAsync(memoryStream, null, options))
                            using (var rotatedBitmap = RotateBitmap(bitmap, matrix))
                            {
                                memoryStream.Dispose();

                                return(await rotatedBitmap.CompressAsync());
                            }
                    }
            }
            catch (Exception e)
            {
                _logger.LogError("Photo rotation error has occurred", e);
                return(memoryStream);
            }
            finally
            {
                exifInterface?.Dispose();
            }
        }