Exemple #1
0
 public Photo(string filename)
 {
     Filename = filename;
     // Get and set picture orienation
     ExifInterface exif = new ExifInterface(Filename);
     mOrientation = exif.GetAttributeInt(ExifInterface.TagOrientation, (int)PhotoOrienation.Normal);
 }
Exemple #2
0
        public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult (requestCode, resultCode, data);

            if (resultCode == Result.Ok) {
                // Make it available in the gallery
            //				Intent mediaScanIntent = new Intent (Intent.ActionMediaScannerScanFile);
            //				Android.Net.Uri contentUri = Android.Net.Uri.FromFile (file);
            //				mediaScanIntent.SetData (contentUri);
            //
            //				Activity.SendBroadcast (mediaScanIntent);
            //
                AttendancePhoto attPhoto = new AttendancePhoto () {
                    photoPath = file.ToString (),
                    stamp = DateTime.Now,
                    subType = currentPhotoSubTypes[spnPhotoSubTypes.SelectedItemPosition].id
                };

                //Latitude and Longitude
                ExifInterface exif = new ExifInterface (attPhoto.photoPath);
                float[] lat_long = new float[2];
                if (exif.GetLatLong (lat_long)) {
                    attPhoto.latitude = lat_long [0];
                    attPhoto.longitude = lat_long [1];
                }

                newAttendancePhotos.Add (attPhoto);
                AttendancePhotoManager.SetCurrentAttendancePhotos (newAttendancePhotos);

                RefreshPhotoList ();
            }

            // Dispose of the Java side bitmap.
            GC.Collect();
        }
		static int? GetRotation(string filePath)
		{
			try
			{
				ExifInterface ei = new ExifInterface(filePath);
				var orientation = (MediaOrientation)ei.GetAttributeInt(ExifInterface.TagOrientation, (int)MediaOrientation.Normal);
				switch (orientation)
				{
				case MediaOrientation.Rotate90:
					return 90;
				case MediaOrientation.Rotate180:
					return 180;
				case MediaOrientation.Rotate270:
					return 270;
				default:
					return null;
				}

			}
			catch (Exception ex)
			{
				//ex.Report();
				return null;
			}
		}
Exemple #4
0
        public static Bitmap GetAndRotateBitmap(string fileName)
        {
            Bitmap bitmap = BitmapFactory.DecodeFile(fileName);

            // Images are being saved in landscape, so rotate them back to portrait if they were taken in portrait
            // See https://forums.xamarin.com/discussion/5409/photo-being-saved-in-landscape-not-portrait
            // See http://developer.android.com/reference/android/media/ExifInterface.html
            using (Matrix mtx = new Matrix())
            {
                if (Android.OS.Build.Product.Contains("Emulator"))
                {
                    mtx.PreRotate(90);
                }
                else
                {
                    ExifInterface exif = new ExifInterface(fileName);
                    var orientation = (Orientation)exif.GetAttributeInt(ExifInterface.TagOrientation, (int)Orientation.Normal);

                    //TODO : handle FlipHorizontal, FlipVertical, Transpose and Transverse
                    switch (orientation)
                    {
                        case Orientation.Rotate90:
                            mtx.PreRotate(90);
                            break;
                        case Orientation.Rotate180:
                            mtx.PreRotate(180);
                            break;
                        case Orientation.Rotate270:
                            mtx.PreRotate(270);
                            break;
                        case Orientation.Normal:
                            // Normal, do nothing
                            break;
                        default:
                            break;
                    }
                }

                if (mtx != null)
                    bitmap = Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, mtx, false);
            }

            return bitmap;
        }
        public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult (requestCode, resultCode, data);

            if (resultCode == Result.Ok) {
                bIsPhotoMake = false;
                // Make it available in the gallery
                Intent mediaScanIntent = new Intent (Intent.ActionMediaScannerScanFile);
                Android.Net.Uri contentUri = Android.Net.Uri.FromFile (file);
                mediaScanIntent.SetData (contentUri);

                Activity.SendBroadcast (mediaScanIntent);

                ExifInterface exif = new ExifInterface (file.ToString ());
                text.Text += String.Format(@"TagGpsLatitude : {0} \n", exif.GetAttribute (ExifInterface.TagGpsLatitude));
                text.Text += String.Format(@"TagGpsLongitude : {0} \n", exif.GetAttribute (ExifInterface.TagGpsLongitude));
                text.Text += String.Format(@"TagGpsDatestamp : {0} \n", exif.GetAttribute (ExifInterface.TagGpsDatestamp));
                text.Text += String.Format(@"TagIso : {0} \n", exif.GetAttribute (ExifInterface.TagIso));
                text.Text += String.Format(@"TagDatetime : {0} \n", exif.GetAttribute (ExifInterface.TagDatetime));

                AttendancePhoto attPhoto = new AttendancePhoto () { id = -1,  photoPath = file.ToString ()};
                DateTime dtStamp;
                if (DateTime.TryParse (exif.GetAttribute (ExifInterface.TagDatetime), out dtStamp)){
                    attPhoto.stamp = dtStamp;
                };

                float gps;
                if (float.TryParse (exif.GetAttribute (ExifInterface.TagGpsLatitude), out gps)){
                    attPhoto.latitude = gps;
                };

                if (float.TryParse (exif.GetAttribute (ExifInterface.TagGpsLongitude), out gps)){
                    attPhoto.longitude = gps;
                };

                attPhoto.latitude = convertToDegree (exif.GetAttribute (ExifInterface.TagGpsLatitude));
                attPhoto.longitude = convertToDegree (exif.GetAttribute (ExifInterface.TagGpsLongitude));

                newAttendancePhotos.Add (attPhoto);
            }

            // Dispose of the Java side bitmap.
            GC.Collect();
        }
		public static Bitmap LoadAndResizeBitmap (this string fileName, int width, int height)
		{

			ExifInterface exif = new ExifInterface (fileName);
			int exifOrientation = exif.GetAttributeInt (
				                      ExifInterface.TagOrientation,
				                      (int)Android.Media.Orientation.Normal);


			int rotate = 0;

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

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

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

			Bitmap bitmap = BitmapFactory.DecodeFile (fileName);
			int w = bitmap.Width;
			int h = bitmap.Height;

			// Setting pre rotate
			Matrix mtx = new Matrix ();
			mtx.PreRotate (rotate);

			// Rotating Bitmap & convert to ARGB_8888, required by tess
			bitmap = Bitmap.CreateBitmap (bitmap, 0, 0, w, h, mtx, false);
			bitmap = bitmap.Copy (Bitmap.Config.Argb8888, true);

			return bitmap;
		}
		public static Bitmap RotateImageIfNeeded(Bitmap bitmap, string path)
		{
			ExifInterface ei = new ExifInterface(path);
			int orientation = ei.GetAttributeInt(ExifInterface.TagOrientation, (int)Android.Media.Orientation.Undefined);

			Bitmap returnBitmap = bitmap;
			switch (orientation)
			{
				case (int)Android.Media.Orientation.Rotate90:
					returnBitmap = RotateImage(bitmap, 90);
					break;
				case (int)Android.Media.Orientation.Rotate180:
					returnBitmap = RotateImage(bitmap, 180);
					break;
				case (int)Android.Media.Orientation.Rotate270:
					returnBitmap = RotateImage(bitmap, 270);
					break;
				default:
					returnBitmap = RotateImage(bitmap, 270);
					break;
			}
			return returnBitmap;
		}
        public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult (requestCode, resultCode, data);

            if (resultCode == Result.Ok) {
                // Make it available in the gallery
                Intent mediaScanIntent = new Intent (Intent.ActionMediaScannerScanFile);
                Android.Net.Uri contentUri = Android.Net.Uri.FromFile (file);
                mediaScanIntent.SetData (contentUri);

                Activity.SendBroadcast (mediaScanIntent);

                ExifInterface exif = new ExifInterface (file.ToString ());
                text.Text += String.Format(@"TagGpsLatitude : {0} \n", exif.GetAttribute (ExifInterface.TagGpsLatitude));
                text.Text += String.Format(@"TagGpsLongitude : {0} \n", exif.GetAttribute (ExifInterface.TagGpsLongitude));
                text.Text += String.Format(@"TagGpsDatestamp : {0} \n", exif.GetAttribute (ExifInterface.TagGpsDatestamp));
                text.Text += String.Format(@"TagIso : {0} \n", exif.GetAttribute (ExifInterface.TagIso));
                text.Text += String.Format(@"TagDatetime : {0} \n", exif.GetAttribute (ExifInterface.TagDatetime));
            }

            // Dispose of the Java side bitmap.
            GC.Collect();
        }
		public static int GetExifRotationDegrees(this string filePath)
		{
			int rotation = 0;
			var exifInt = new ExifInterface(filePath);
			int exifRotation = exifInt.GetAttributeInt(ExifInterface.TagOrientation, (int)Orientation.Normal);

			switch (exifRotation)
			{
				case (int) Orientation.Rotate270:
					rotation = 270;
					break;
				case (int) Orientation.Rotate180:
					rotation = 180;
					break;
				case (int) Orientation.Rotate90:
					rotation = 90;
					break;
				default:
					return 0;
			}

			return rotation;
		}
Exemple #10
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            RequestWindowFeature(Android.Views.WindowFeatures.NoTitle);
			this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
            SetContentView(Resource.Layout.cropimage);

            imageView = FindViewById<CropImageView>(Resource.Id.image);

            showStorageToast(this);

            Bundle extras = Intent.Extras;

            if (extras != null)
            {
                imagePath = extras.GetString("image-path");

                saveUri = getImageUri(imagePath);
                if (extras.GetString(MediaStore.ExtraOutput) != null)
                {
                    saveUri = getImageUri(extras.GetString(MediaStore.ExtraOutput));
                }

                bitmap = getBitmap(imagePath);

                aspectX = extras.GetInt("aspectX");
                aspectY = extras.GetInt("aspectY");
                outputX = extras.GetInt("outputX");
                outputY = extras.GetInt("outputY");
                scale = extras.GetBoolean("scale", true);
                scaleUp = extras.GetBoolean("scaleUpIfNeeded", true);

                if (extras.GetString("outputFormat") != null)
                {
                    outputFormat = Bitmap.CompressFormat.ValueOf(extras.GetString("outputFormat"));
                }
            }

            if (bitmap == null)
            {
                Finish();
                return;
            }

            Window.AddFlags(WindowManagerFlags.Fullscreen);


            FindViewById<Button>(Resource.Id.discard).Click += (sender, e) => { SetResult(Result.Canceled); Finish(); };
            FindViewById<Button>(Resource.Id.save).Click += (sender, e) => { onSaveClicked(); };

            FindViewById<Button>(Resource.Id.rotateLeft).Click += (o, e) =>
            {
                bitmap = Util.rotateImage(bitmap, -90);
                RotateBitmap rotateBitmap = new RotateBitmap(bitmap);
                imageView.SetImageRotateBitmapResetBase(rotateBitmap, true);
                addHighlightView();
            };

            FindViewById<Button>(Resource.Id.rotateRight).Click += (o, e) =>
            {
                bitmap = Util.rotateImage(bitmap, 90);
                RotateBitmap rotateBitmap = new RotateBitmap(bitmap);
                imageView.SetImageRotateBitmapResetBase(rotateBitmap, true);
                addHighlightView();
            };

			ExifInterface exif = new ExifInterface(imagePath);
			string orientation = exif.GetAttribute(ExifInterface.TagOrientation);

			switch(orientation) {
			case "6" : // portrait
				bitmap = Util.rotateImage(bitmap, -90);
				break;
			case "1" : // landscape
				break;
			default :
				bitmap = Util.rotateImage(bitmap, -90);
				break;
			}		

            imageView.SetImageBitmapResetBase(bitmap, true);
            addHighlightView();
        }
        /// <summary>
        /// Called after the user image is captured
        /// Stores the image, displays it on the GUI, and submits it for facial recognition
        /// </summary>
        /// <param name="requestCode"></param>
        /// <param name="resultCode"></param>
        /// <param name="data"></param>
        protected override async void OnActivityResult( int requestCode, Result resultCode, Intent data )
        {

            base.OnActivityResult( requestCode, resultCode, data );

            // Make it available in the gallery
            Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);

            // Gets the image file
            Android.Net.Uri contentUri = Android.Net.Uri.FromFile(App._file);

            // Put image file into media database
            mediaScanIntent.SetData( contentUri );
            SendBroadcast( mediaScanIntent );

            // Determine the dimensions to resize the image to
            // Loading the full sized image will consume to much memory and cause the application to crash
            int ImageHeight = Resources.DisplayMetrics.HeightPixels;
            int ImageWidth = UserImageView.Height;

            // Load the image
            App.bitmap = App._file.Path.LoadAndResizeBitmap( ImageWidth, ImageHeight );

            // Check that the image was loaded successfull
            if (App.bitmap != null)
            {
                // Check the image orientation
                ExifInterface exif = new ExifInterface( App._file.AbsoluteFile.ToString() );
                int Orientation = Convert.ToInt32( exif.GetAttribute( ExifInterface.TagOrientation ) );
                App.bitmap = BitmapHelpers.RotateBitmap( App.bitmap, Orientation );

                // Set the bitmap to the image view
                UserImageView.SetImageBitmap( App.bitmap );

                // Submit the image for facial recognition matching
                string recognizeResult = await RecognizeImage( App.bitmap );

                // Remove the image data from memory
                App.bitmap = null;


                // Set the match name
                MatchTextView.Text = recognizeResult;


                // Get the match image from the name
                string MatchImageURL;
                CelebrityImage.TryGetValue( recognizeResult, out MatchImageURL );
                if (MatchImageURL != null)
                {
                    Bitmap CelebrityImageBitmap = BitmapHelpers.GetImageBitmapFromUrl( MatchImageURL );
                    MatchImageView.SetImageBitmap( CelebrityImageBitmap );
                }


            }
            

            // Dispose of the Java side bitmap
            GC.Collect();
        }
        protected override void OnCreate(Bundle bundle) {
            RequestWindowFeature(WindowFeatures.NoTitle);
            base.OnCreate(bundle);
            this.SetContentView(Resource.Layout.SignaturePad);

            SignaturePadOrientation actualOrientation = SignaturePadOrientation.Automatic;

            this.currentConfig = new SignaturePadConfiguration();
            this.currentConfig.LoadFromIntent(this.Intent);

            var rootView = this.FindViewById<RelativeLayout>(Resource.Id.rootView);
            this.signatureView = this.FindViewById<SignaturePadView>(Resource.Id.signatureView);
            this.btnSave = this.FindViewById<Button>(Resource.Id.btnSave);
            this.btnCancel = this.FindViewById<Button>(Resource.Id.btnCancel);

            var cfg = currentConfig;
            rootView.SetBackgroundColor(cfg.BackgroundColor.ToAndroidColor());
            this.signatureView.BackgroundColor = cfg.SignatureBackgroundColor.ToAndroidColor();


            this.signatureView.Caption.Text = cfg.CaptionText;
            this.signatureView.Caption.SetTextColor(cfg.CaptionTextColor.ToAndroidColor());
            this.signatureView.ClearLabel.Text = cfg.ClearText;
            this.signatureView.ClearLabel.SetTextColor(cfg.ClearTextColor.ToAndroidColor());
            this.signatureView.SignatureLineColor = cfg.SignatureLineColor.ToAndroidColor();
            this.signatureView.SignaturePrompt.Text = cfg.PromptText;
            this.signatureView.SignaturePrompt.SetTextColor(cfg.PromptTextColor.ToAndroidColor());
            this.signatureView.StrokeColor = cfg.StrokeColor.ToAndroidColor();
            this.signatureView.StrokeWidth = cfg.StrokeWidth;


            this.btnSave.Text = cfg.SaveText;
            this.btnCancel.Text = cfg.CancelText;
            if (string.IsNullOrWhiteSpace(cfg.CancelText)) {
                this.btnCancel.Visibility = ViewStates.Invisible;
            }

            var exif = new ExifInterface(cfg.BackgroundImage);
            var orientation = exif.GetAttribute(ExifInterface.TagOrientation);
            var width = exif.GetAttributeInt(ExifInterface.TagImageWidth, 100);
            var height = exif.GetAttributeInt(ExifInterface.TagImageLength, 80);            
            switch (orientation) {
                case "1": // landscape
                case "3": // landscape
                    actualOrientation = SignaturePadOrientation.Landscape;
                    break;

                case "8":
                case "4":
                case "6": // portrait
                    actualOrientation = SignaturePadOrientation.Portrait;
                    break;

                case "0": //undefined
                default:
                    if (width > height)
                        actualOrientation = SignaturePadOrientation.Landscape;
                    else
                        actualOrientation = SignaturePadOrientation.Portrait;
                    break;
            }

            switch (actualOrientation) {
                case SignaturePadOrientation.Landscape:
                    this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;
                    break;
                case SignaturePadOrientation.Portrait:
                    this.RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
                    break;

            }


            this.signatureView.BackgroundImageView.LayoutParameters.Height = ViewGroup.LayoutParams.FillParent;
            this.signatureView.BackgroundImageView.LayoutParameters.Width = ViewGroup.LayoutParams.FillParent;


            this.signatureView.BackgroundImageView.ViewTreeObserver.GlobalLayout += (sender, e) =>  //also tried with _View
            {

                var newSize = new Size(this.signatureView.Width, this.signatureView.Height);
                if (newSize.Width > 0 && !hasBackground) {
                    if (cfg.Points != null && cfg.Points.Count() > 0) {

                        var points = cfg.Points.Select(i => i.GetPointF()).ToArray();
                        this.signatureView.LoadPoints(points);
                    } else {
                    }
                    //Get a smaller image if needed (memory optimization)
                    var bm = LoadAndResizeBitmap(cfg.BackgroundImage, newSize);
                    if (bm != null) {
                        hasBackground = true;
                        switch (cfg.BackgroundImageSize) {
                            case SignaturePadBackgroundSize.Fill:
                                this.signatureView.BackgroundImageView.SetScaleType(ImageView.ScaleType.FitXy);
                                this.signatureView.BackgroundImageView.SetAdjustViewBounds(true);
                                break;
                            case SignaturePadBackgroundSize.Stretch:
                                this.signatureView.BackgroundImageView.SetScaleType(ImageView.ScaleType.FitXy);
                                break;

                        }
                        this.signatureView.BackgroundImageView.SetImageBitmap(bm);
                    }
                }
            };


        }
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            if ((resultCode == Result.Ok) && (data != null))
            {
                if (requestCode == PickImageId)
                {
                    Uri uri = data.Data;
                    Bitmap tempBitmap = BitmapFactory.DecodeFile(GetPathToImage(uri));

                    //resize
                    int newHeight = ConvertDptoPx(60);
                    int newWidth = (int) (((float) tempBitmap.Width) / ((float) tempBitmap.Height) * newHeight);

                    //scale
                    float scaleWidth = ((float) newWidth) / tempBitmap.Width;
                    float scaleHeight = ((float) newHeight) / tempBitmap.Height;

                    Matrix matrix = new Matrix();
                    matrix.PostScale(scaleWidth, scaleHeight);

                    //rotate
                    ExifInterface exif = new ExifInterface(GetPathToImage(uri));
                    int orientation = exif.GetAttributeInt(ExifInterface.TagOrientation, 1);
                    switch (orientation)
                    {
                        case 3:
                            matrix.PostRotate(180);
                            break;
                        case 6:
                            matrix.PostRotate(90);
                            break;
                        case 8:
                            matrix.PostRotate(270);
                            break;
                    }

                    _bitmap = Bitmap.CreateBitmap(tempBitmap, 0, 0, tempBitmap.Width, tempBitmap.Height, matrix, false);
                    tempBitmap.Recycle();
                    _imageView.SetImageBitmap(_bitmap);
                }

                else if (requestCode == PickContactsId)
                {
                    _participantsAdapter.Items.Clear();

                    string intentString = data.GetStringExtra("New participants");
                    if (intentString != string.Empty)
                    {
                        string[] contactStrings = intentString.Split('|');

                        for (int i = 0; i < contactStrings.Length; i++)
                        {
                            string[] contactAttr = contactStrings[i].Split(',');

                            _participantsAdapter.Items.Add(new ListItem(contactAttr[0], int.Parse(contactAttr[1]))); // 0 = naam, 1 = image
                        }
                    }

                    _participantsAdapter.NotifyDataSetChanged();
                    _participantsRecyclerView.LayoutParameters.Height = ConvertDptoPx(listItemHeight * _participantsAdapter.Items.Count);
                    _participantsRecyclerView.Invalidate ();
                    _scrollView.Invalidate();
                    _scrollView.RequestLayout();
                }
            }
        }
        static int? GetRotation(string filePath)
        {
            try
            {
                var ei = new ExifInterface(filePath);
                var orientation = (Orientation)ei.GetAttributeInt(ExifInterface.TagOrientation, (int)Orientation.Normal);
                switch (orientation)
                {
                    case Orientation.Rotate90:
                        return 90;
                    case Orientation.Rotate180:
                        return 180;
                    case Orientation.Rotate270:
                        return 270;
                    default:
                        return null;
                }

            }
            catch (Exception ex)
            {
#if DEBUG
                throw ex;
#else
            return null;
#endif
            }
        }
        int NeededRotation(Java.IO.File ff)
        {
            try
            {
                // extract the header info
                ExifInterface exif = new ExifInterface( ff.AbsolutePath );

                // determine how we should rotate the image
                int orientation = exif.GetAttributeInt( ExifInterface.TagOrientation, 0 );
                switch( orientation )
                {
                    case 3: return 180;
                    case 6: return 90;
                    case 8: return 270;
                }

                return 0;

            } 
            catch (Exception )
            {
            }

            return 0;
        }
Exemple #16
0
        private Bitmap LoadAndResizeBitmap()
        {
            if (Path.StartsWith("http"))
            {
                //var webImage = GetImageBitmapFromUrl(Path);
                //return Bitmap.CreateScaledBitmap(webImage, _screenWidth, _screenHeight, false);
                return GetImageBitmapFromUrl(Path);
            }

            // First we get the the dimensions of the file on disk
            BitmapFactory.Options options = new BitmapFactory.Options { InJustDecodeBounds = true };
            BitmapFactory.DecodeFile(Path, 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 > _screenHeight || outWidth > _screenWidth)
            {
                inSampleSize = outWidth > outHeight
                               ? outHeight / _screenHeight
                               : outWidth / _screenWidth;
            }

            // Now we will load the image and have BitmapFactory resize it for us.
            options.InSampleSize = inSampleSize;
            options.InJustDecodeBounds = false;
            Bitmap resizedBitmap = BitmapFactory.DecodeFile(Path, options);

            // Images are being saved in landscape, so rotate them back to portrait if they were taken in portrait
            Matrix mtx = new Matrix();
            ExifInterface exif = new ExifInterface(Path);
            string orientation = exif.GetAttribute(ExifInterface.TagOrientation);
            switch (orientation)
            {
                case "6": // portrait
                    mtx.PreRotate(90);
                    resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
                    mtx.Dispose();
                    mtx = null;
                    break;
                case "1": // 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;
        }
        private async Task GeoTagPhotoAsync()
        {
            // see if the photo already contains geo coords
            var exif = new ExifInterface(_file.Path);
            if (!string.IsNullOrWhiteSpace(exif.GetAttribute(ExifInterface.TagGpsLatitude)))
                return;

            RequestCurrentLocation();
            var location = await _locationTCS.Task;

            try
            {
                int num1Lat = (int)Math.Floor(location.Latitude);
                int num2Lat = (int)Math.Floor((location.Latitude - num1Lat) * 60);
                double num3Lat = (location.Latitude - ((double)num1Lat + ((double)num2Lat / 60))) * 3600000;

                int num1Lon = (int)Math.Floor(location.Longitude);
                int num2Lon = (int)Math.Floor((location.Longitude - num1Lon) * 60);
                double num3Lon = (location.Longitude - ((double)num1Lon + ((double)num2Lon / 60))) * 3600000;

                exif.SetAttribute(ExifInterface.TagGpsLatitude, num1Lat + "/1," + num2Lat + "/1," + num3Lat + "/1000");
                exif.SetAttribute(ExifInterface.TagGpsLongitude, num1Lon + "/1," + num2Lon + "/1," + num3Lon + "/1000");


                if (location.Latitude > 0)
                {
                    exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "N");
                }
                else
                {
                    exif.SetAttribute(ExifInterface.TagGpsLatitudeRef, "S");
                }

                if (location.Longitude > 0)
                {
                    exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "E");
                }
                else
                {
                    exif.SetAttribute(ExifInterface.TagGpsLongitudeRef, "W");
                }

                exif.SaveAttributes();
            }
            catch (Java.IO.IOException)
            {
                // location will not be available on this image, but continue
            }
        }
Exemple #18
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();
            ExifInterface exif = new ExifInterface(fileName);
            var orientation = (Orientation)exif.GetAttributeInt(ExifInterface.TagOrientation, (int)Orientation.Undefined);

            switch (orientation)
            {
                case Orientation.Undefined: // Nexus 7 landscape...
                    break;
                case Orientation.Normal: // landscape
                    break;
                case Orientation.FlipHorizontal:
                    break;
                case Orientation.Rotate180:
                    mtx.PreRotate(180);
                    resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
                    mtx.Dispose();
                    mtx = null;
                    break;
                case Orientation.FlipVertical:
                    break;
                case Orientation.Transpose:
                    break;
                case Orientation.Rotate90: // portrait
                    mtx.PreRotate(90);
                    resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
                    mtx.Dispose();
                    mtx = null;
                    break;
                case Orientation.Transverse:
                    break;
                case Orientation.Rotate270: // might need to flip horizontally too...
                    mtx.PreRotate(270);
                    resizedBitmap = Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
                    mtx.Dispose();
                    mtx = null;
                    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 OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
        {
            FileOutputStream output = null;
            string path = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "Images");
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            string filename = PictureName + number.ToString() + ".jpg";
            if (data != null)
            {
                fullFilename = System.IO.Path.Combine(path, filename);
                number++;
                try
                {
                    output = new FileOutputStream(fullFilename);
                    output.Write(data);
                    output.Close();
                }
                catch (FileNotFoundException)
                {
                    RunOnUiThread(delegate
                    {
                        GeneralUtils.Alert(context, Application.Context.Resources.GetString(Resource.String.commonError),
                            Application.Context.Resources.GetString(Resource.String.errorFileTransfer));
                    });
                    return;
                }
                catch (IOException)
                {
                    RunOnUiThread(delegate
                    {
                        GeneralUtils.Alert(context, Application.Context.Resources.GetString(Resource.String.commonError),
                            Application.Context.Resources.GetString(Resource.String.errorNoImagesTaken));
                    });
                    isRunning = true;
                    camera.StartPreview();
                    return;
                }
                catch (Exception e)
                {
                    #if DEBUG
                    System.Diagnostics.Debug.WriteLine("Exception thrown - {0}", e.Message);
                    #endif
                    return;
                }

                var f = new File(fullFilename);
                try
                {
                    var exifInterface = new ExifInterface(f.CanonicalPath);
                    exifInterface.GetAttribute(ExifInterface.TagModel);
                    var latLong = new float[2];
                    exifInterface.GetLatLong(latLong);
                    exifInterface.SetAttribute(ExifInterface.TagMake, "Phone picture");
                    exifInterface.SetAttribute(ExifInterface.TagDatetime, DateTime.Now.ToString());
                }
                catch (IOException)
                {
                    RunOnUiThread(delegate
                    {
                        GeneralUtils.Alert(context, Application.Context.Resources.GetString(Resource.String.commonError),
                            Application.Context.Resources.GetString(Resource.String.errorStoreEXIF));
                    });
                    isRunning = true;
                    camera.StartPreview();
                    return;
                }
            }
            RunOnUiThread(() => Toast.MakeText(context, Application.Context.Resources.GetString(Resource.String.commonPictureTaken), ToastLength.Short).Show());
            isRunning = true;
            camera.StartPreview();
            return;
        }
        private Android.Graphics.Bitmap LoadAndResizeBitmap(string fileName, Size newSize) {
            var exif = new ExifInterface(fileName);

            var width = exif.GetAttributeInt(ExifInterface.TagImageWidth, 100);
            var height = exif.GetAttributeInt(ExifInterface.TagImageLength, 80);
            var orientation = exif.GetAttribute(ExifInterface.TagOrientation);


            // We calculate the ratio that we need to resize the image by
            // in order to fit the requested dimensions.

            var inSampleSize = 1.0;

            if (newSize.Height < height || newSize.Width < width) {
                inSampleSize = newSize.Width > newSize.Height
                    ? newSize.Height / height
                        : newSize.Width / width;
            }

            var options = new Android.Graphics.BitmapFactory.Options {
                InJustDecodeBounds = false,
                InSampleSize = (int)inSampleSize
            };
            // Now we will load the image and have BitmapFactory resize it for us.
            var resizedBitmap = Android.Graphics.BitmapFactory.DecodeFile(fileName, options);

            var rotate = false;
            
            switch (orientation) {
                case "1": // landscape
                case "3": // landscape
                    if (width < height)
                        rotate = true;
                    break;
                case "8":
                case "4":
                case "6": // portrait
                    if (width > height)
                        rotate = true;
                    break;
                case "0": //undefined
                default:
                    break;
            }

            if (rotate) {
                var mtx = new Android.Graphics.Matrix();
                mtx.PreRotate(90);
                resizedBitmap = Android.Graphics.Bitmap.CreateBitmap(resizedBitmap, 0, 0, resizedBitmap.Width, resizedBitmap.Height, mtx, false);
                mtx.Dispose();
                mtx = null;

            }


            return resizedBitmap;
        }
		public async  Task<bool> DownloadFiles ( List<string> downloadUrlList, CancellationToken cancelToken )
		{
			int imgMaxWidth = (int)(App.screenWidth * App.screenDensity);
			int imgMaxHeight = (int)(App.screenHeight * .50 * App.screenDensity);
			int streamLength = 0;
			try 
			{
				foreach (var item in downloadUrlList)
				{
					cancelToken.ThrowIfCancellationRequested();

					string fileName = System.IO.Path.GetFileName(item);
					WebClient webClient = new WebClient();
					if(  !File.Exists( App.DownloadsPath + fileName ))
					{	
						await webClient.DownloadFileTaskAsync ( item,  App.DownloadsPath + fileName );
						webClient.Dispose();

						try {

							BitmapFactory.Options imgOptions = new BitmapFactory.Options();
							imgOptions.InJustDecodeBounds = true;
							MemoryStream memStream = null;
							await BitmapFactory.DecodeFileAsync(App.DownloadsPath + fileName,imgOptions);

							if(imgOptions.OutHeight <= 5000 && imgOptions.OutWidth <= 5000 )
							{
								using (FileStream fs = File.OpenRead(App.DownloadsPath + fileName))
								{
									streamLength = (int)fs.Length;
									if(streamLength < 5242880) // 5MB = 5242880 byts, 2.5 MB = 2621440 byts
									{
										memStream = new MemoryStream();
										fs.CopyTo(memStream);
									}
									fs.Close();
									fs.Dispose();
								}

								if (memStream != null &&  memStream.ToArray().Length > 0) 
								{
									Bitmap originalImage = null;
									streamLength = (int)memStream.ToArray().Length;
									if(streamLength < 4242880 ) // 5MB = 5242880 byts, 2.5 MB = 2621440 byts
									{
										try {
											originalImage  = BitmapFactory.DecodeByteArray(memStream.ToArray(), 0, memStream.ToArray().Length);
										} 
										catch (Exception ex) 
										{
											var test = ex.Message;
											FileStream fstream = new FileStream(App.DownloadsPath + fileName, FileMode.Create);
											fstream.Close();
											fstream.Dispose();
											fstream = null;
											continue;
										}
										if(originalImage.Height > originalImage.Width)
										{
											if (originalImage.Height > 300 || originalImage.Width > 300) {
												originalImage = Bitmap.CreateScaledBitmap(originalImage,  imgMaxWidth, imgMaxHeight, true);
											}
										}
										else
										{
											if (originalImage.Width > imgMaxHeight || originalImage.Height > imgMaxWidth) {
												originalImage = Bitmap.CreateScaledBitmap(originalImage,  imgMaxWidth, imgMaxWidth, true);
											}
										}


										int compressionRate  = 100;

										#region compression ratio
										if (streamLength < 20000) {
											compressionRate = 100;
										}
										else if (streamLength < 40000) {
											compressionRate = App.screenDensity > 2 ? 100: 95;
										}
										else if (streamLength < 50000) {
											compressionRate = App.screenDensity > 2 ? 100: 91;
										}
										else if (streamLength < 100000) {
											compressionRate = App.screenDensity > 2 ? 100: 90;
										}
										else if (streamLength < 200000) {
											compressionRate = App.screenDensity > 2 ? 99: 89;
										}
										else if (streamLength <300000) {
											compressionRate = App.screenDensity > 2 ? 98: 88;
										}
										else if (streamLength < 400000) {
											compressionRate = App.screenDensity > 2 ? 97: 87;
										}
										else if (streamLength < 500000) {
											compressionRate = App.screenDensity > 2 ? 96: 86;
										}
										else if (streamLength < 600000) {
											compressionRate = App.screenDensity > 2 ? 95: 86;
										}
										else if (streamLength < 700000) {
											compressionRate = App.screenDensity > 2 ? 94: 86;
										}
										else if (streamLength < 900000) {
											compressionRate = App.screenDensity > 2 ? 92: 86;
										}
										else if (streamLength < 1000000) {
											compressionRate = App.screenDensity > 2 ? 90: 86;
										}
										else if (streamLength < 2000000) {
											compressionRate = App.screenDensity > 2 ? 85: 86;
										}
										else {
											compressionRate = App.screenDensity > 2 ? 80: 85;
										}
										#endregion

										ExifInterface exif = new ExifInterface(App.DownloadsPath+fileName);
										var orientation = exif.GetAttributeInt(ExifInterface.TagOrientation, (int)Android.Media.Orientation.Normal);
										int orientationP = exif.GetAttributeInt (ExifInterface.TagOrientation, 0);
										switch (orientation) 
										{
										case (int)Android.Media.Orientation.Rotate180:
											originalImage = changeOrientation (App.DownloadsPath + fileName, originalImage, orientationP);
											break;
										case (int) Android.Media.Orientation.Rotate270:
											originalImage = changeOrientation (App.DownloadsPath + fileName, originalImage, orientationP);
											break;
										case (int)Android.Media.Orientation.Rotate90:
											originalImage = changeOrientation (App.DownloadsPath + fileName, originalImage, orientationP);
											break;
										default:
											break;
										}
										exif.Dispose();
										exif = null;

										FileStream stream = new FileStream(App.DownloadsPath + fileName, FileMode.Create);
										originalImage.Compress(Bitmap.CompressFormat.Jpeg, compressionRate, stream);
										stream.Close();
										stream.Dispose();
										stream = null;
										memStream.Dispose();
										memStream = null;
										//resizedImage.Dispose();
										//resizedImage = null;
										originalImage.Recycle();
										originalImage.Dispose();
										originalImage = null;
									}
									else
									{
										FileStream fstream = new FileStream(App.DownloadsPath + fileName, FileMode.Create);
										fstream.Close();
										fstream.Dispose();
										fstream = null;
									}
								}
							}
							else
							{
								FileStream fstream = new FileStream(App.DownloadsPath + fileName, FileMode.Create);
								fstream.Close();
								fstream.Dispose();
								fstream = null;
							}
						} catch (Exception ex) {
							var test = ex.Message;
							FileStream fstream = new FileStream(App.DownloadsPath + fileName, FileMode.Create);
							fstream.Close();
							fstream.Dispose();
							fstream = null;
						}
					}// if file exists

				} //foreach
				return true;
			} 
			catch (Exception ex) 
			{
				Debug.WriteLine ( ex.Message );
				return false;
			}

		}