Пример #1
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            base.OnCreateView(inflater, container, savedInstanceState);
            var view = inflater.Inflate(Resource.Layout.ConfirmationsLayout, null, true);

            signatureImage = view.FindViewById <ImageView> (Resource.Id.confirmationsSignature);

            photoListView            = view.FindViewById <ListView> (Resource.Id.confirmationPhotoList);
            photoListView.ItemClick += (sender, e) => {
                var image = view.FindViewById <ImageView> (Resource.Id.photoListViewImage);
                if (image != null)
                {
                    int index = (int)image.Tag;
                    var photo = Photos.ElementAtOrDefault(index);
                    photoDialog            = new PhotoDialog(Activity);
                    photoDialog.Activity   = Activity;
                    photoDialog.Assignment = Assignment;
                    photoDialog.Photo      = photo;
                    photoDialog.Show();
                }
            };

            var addPhoto = view.FindViewById <Button> (Resource.Id.confirmationsAddPhoto);

            if (Assignment != null)
            {
                addPhoto.Enabled = !Assignment.IsHistory;
            }

            addPhoto.Click += (sender, e) => {
                var choices = new List <string> ();
                choices.Add(Resources.GetString(Resource.String.Gallery));
                if (mediaPicker.IsCameraAvailable)
                {
                    choices.Add(Resources.GetString(Resource.String.Camera));
                }

                AlertDialog.Builder takePictureDialog = new AlertDialog.Builder(Activity);
                takePictureDialog.SetTitle("Select:");
                takePictureDialog.SetItems(choices.ToArray(), (innerSender, innerE) => {
                    if (innerE.Which == 0)
                    {
                        //gallery
                        mediaPicker.PickPhotoAsync().ContinueWith(t => {
                            if (t.IsCanceled)
                            {
                                return;
                            }
                            Activity.RunOnUiThread(() => {
                                photoDialog             = new PhotoDialog(Activity);
                                photoDialog.Activity    = Activity;
                                photoDialog.Assignment  = Assignment;
                                photoDialog.PhotoStream = t.Result.GetStream();
                                photoDialog.Show();
                            });
                        });
                    }
                    else if (innerE.Which == 1)
                    {
                        //camera
                        StoreCameraMediaOptions options = new StoreCameraMediaOptions();
                        options.Directory = "FieldService";
                        options.Name      = "FieldService.jpg";
                        mediaPicker.TakePhotoAsync(options).ContinueWith(t => {
                            if (t.IsCanceled)
                            {
                                return;
                            }
                            Activity.RunOnUiThread(() => {
                                photoDialog             = new PhotoDialog(Activity);
                                photoDialog.Activity    = Activity;
                                photoDialog.Assignment  = Assignment;
                                photoDialog.PhotoStream = t.Result.GetStream();
                                photoDialog.Show();
                            });
                        });
                    }
                });
                takePictureDialog.Show();
            };

            var addSignature = view.FindViewById <Button> (Resource.Id.confirmationsAddSignature);

            if (Assignment != null)
            {
                addSignature.Enabled = !Assignment.IsHistory;
            }

            addSignature.Click += (sender, e) => {
                signatureDialog            = new SignatureDialog(Activity);
                signatureDialog.Activity   = Activity;
                signatureDialog.Assignment = Assignment;
                signatureDialog.Show();
            };

            var completeSignature = view.FindViewById <Button> (Resource.Id.confirmationsComplete);

            if (Assignment != null)
            {
                completeSignature.Enabled = Assignment.CanComplete;
            }

            completeSignature.Click += (sender, e) => {
                if (assignmentViewModel.Signature == null)
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
                    builder.SetTitle(string.Empty).
                    SetMessage("No signature!").
                    SetPositiveButton("Ok", (innerSender, innere) => {}).
                    Show();
                    return;
                }
                completeSignature.Enabled = false;
                Assignment.Status         = AssignmentStatus.Complete;
                assignmentViewModel.SaveAssignmentAsync(Assignment).ContinueWith(_ => {
                    Activity.RunOnUiThread(() => {
                        completeSignature.Enabled = true;
                        Activity.Finish();
                    });
                });
            };

            ReloadListView();
            ReloadSignature();

            return(view);
        }
Пример #2
0
        /// <summary>
        /// Take a photo async with specified options
        /// </summary>
        /// <param name="options">Camera Media Options</param>
        /// <returns>Media file of photo or null if canceled</returns>
        public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options)
        {
            if (!IsCameraAvailable)
            {
                throw new NotSupportedException();
            }

            if (!(await RequestCameraPermissions()))
            {
                return(null);
            }


            VerifyOptions(options);

            var media = await TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options);

            if (string.IsNullOrWhiteSpace(media?.Path))
            {
                return(media);
            }

            if (options.SaveToAlbum)
            {
                try
                {
                    var fileName  = System.IO.Path.GetFileName(media.Path);
                    var publicUri = MediaPickerActivity.GetOutputMediaFile(context, options.Directory ?? "temp", fileName, true, true);
                    using (System.IO.Stream input = File.OpenRead(media.Path))
                        using (System.IO.Stream output = File.Create(publicUri.Path))
                            input.CopyTo(output);

                    media.AlbumPath = publicUri.Path;

                    var f = new Java.IO.File(publicUri.Path);

                    //MediaStore.Images.Media.InsertImage(context.ContentResolver,
                    //    f.AbsolutePath, f.Name, null);

                    try
                    {
                        Android.Media.MediaScannerConnection.ScanFile(context, new[] { f.AbsolutePath }, null, context as MediaPickerActivity);

                        ContentValues values = new ContentValues();
                        values.Put(MediaStore.Images.Media.InterfaceConsts.Title, System.IO.Path.GetFileNameWithoutExtension(f.AbsolutePath));
                        values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty);
                        values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
                        values.Put(MediaStore.Images.ImageColumns.BucketId, f.ToString().ToLowerInvariant().GetHashCode());
                        values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, f.Name.ToLowerInvariant());
                        values.Put("_data", f.AbsolutePath);

                        var cr = context.ContentResolver;
                        cr.Insert(MediaStore.Images.Media.ExternalContentUri, values);
                    }
                    catch (Exception ex1)
                    {
                        Console.WriteLine("Unable to save to scan file: " + ex1);
                    }

                    var contentUri      = Android.Net.Uri.FromFile(f);
                    var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile, contentUri);
                    context.SendBroadcast(mediaScanIntent);
                }
                catch (Exception ex2)
                {
                    Console.WriteLine("Unable to save to gallery: " + ex2);
                }
            }

            //check to see if we need to rotate if success


            try
            {
                var exif = new ExifInterface(media.Path);
                if (options.RotateImage)
                {
                    await FixOrientationAndResizeAsync(media.Path, options, exif);
                }
                else
                {
                    await ResizeAsync(media.Path, options.PhotoSize, options.CompressionQuality, options.CustomPhotoSize, exif);
                }
                SetMissingMetadata(exif, options.Location);
                exif.SaveAttributes();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to check orientation: " + ex);
            }

            return(media);
        }
Пример #3
0
        /// <summary>
        /// This method takes a picture.
        /// Right now the parameter is not evaluated.
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task <StorageFile> CaptureFileAsync(CameraCaptureUIMode mode, StoreCameraMediaOptions options)
        {
            var t = IsStopped();

            Mode = mode;
            if (Mode == CameraCaptureUIMode.Photo)
            {
                camerButton.Icon = new SymbolIcon(Symbol.Camera);
            }
            else if (Mode == CameraCaptureUIMode.Video)
            {
                camerButton.Icon = new SymbolIcon(Symbol.Video);
            }
            Options = options;
            // Create new MediaCapture
            MyMediaCapture = new MediaCapture();
            var videoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

            var backCamera = videoDevices.FirstOrDefault(
                item => item.EnclosureLocation != null &&
                item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back);

            var frontCamera = videoDevices.FirstOrDefault(
                item => item.EnclosureLocation != null &&
                item.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);

            var captureSettings = new MediaCaptureInitializationSettings();

            if (options.DefaultCamera == CameraDevice.Front && frontCamera != null)
            {
                captureSettings.VideoDeviceId = frontCamera.Id;
            }
            else if (options.DefaultCamera == CameraDevice.Rear && backCamera != null)
            {
                captureSettings.VideoDeviceId = backCamera.Id;
            }
            await MyMediaCapture.InitializeAsync(captureSettings);


            displayInfo.OrientationChanged += DisplayInfo_OrientationChanged;

            DisplayInfo_OrientationChanged(displayInfo, null);

            // Assign to Xaml CaptureElement.Source and start preview
            myCaptureElement.Source = MyMediaCapture;

            // show preview
            await MyMediaCapture.StartPreviewAsync();

            // now wait until stopflag shows that someone took a picture
            await t;

            // picture has been taken
            // stop preview

            await CleanUpAsync();

            // go back
            CurrentWindow.Content = originalFrame;

            mainGrid.Children.Remove(this);

            return(file);
        }
Пример #4
0
        internal MediaPickerDelegate(UIViewController viewController, UIImagePickerControllerSourceType sourceType, StoreCameraMediaOptions options)
        {
            this.viewController = viewController;
            this.source         = sourceType;
            this.options        = options ?? new StoreCameraMediaOptions();

            if (viewController != null)
            {
                UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications();
                this.observer = NSNotificationCenter.DefaultCenter.AddObserver(UIDevice.OrientationDidChangeNotification, DidRotate);
            }
        }
Пример #5
0
        /// <summary>
        /// Take a photo async with specified options
        /// </summary>
        /// <param name="options">Camera Media Options</param>
        /// <returns>Media file of photo or null if canceled</returns>
        public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options)
        {
            if (!initialized)
            {
                await Initialize();
            }

            if (!IsCameraAvailable)
            {
                throw new NotSupportedException();
            }

            options.VerifyOptions();

            var capture = new CameraCaptureUI();

            capture.PhotoSettings.Format        = CameraCaptureUIPhotoFormat.Jpeg;
            capture.PhotoSettings.MaxResolution = GetMaxResolution(options?.PhotoSize ?? PhotoSize.Full, options?.CustomPhotoSize ?? 100);
            //we can only disable cropping if resolution is set to max
            if (capture.PhotoSettings.MaxResolution == CameraCaptureUIMaxPhotoResolution.HighestAvailable)
            {
                capture.PhotoSettings.AllowCropping = options?.AllowCropping ?? true;
            }


            var result = await capture.CaptureFileAsync(CameraCaptureUIMode.Photo);

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

            var folder = ApplicationData.Current.LocalFolder;

            var path          = options.GetFilePath(folder.Path);
            var directoryFull = Path.GetDirectoryName(path);
            var newFolder     = directoryFull.Replace(folder.Path, string.Empty);

            if (!string.IsNullOrWhiteSpace(newFolder))
            {
                await folder.CreateFolderAsync(newFolder, CreationCollisionOption.OpenIfExists);
            }

            folder = await StorageFolder.GetFolderFromPathAsync(directoryFull);

            var filename = Path.GetFileName(path);

            string aPath = null;

            if (options?.SaveToAlbum ?? false)
            {
                try
                {
                    var fileNameNoEx = Path.GetFileNameWithoutExtension(path);
                    var copy         = await result.CopyAsync(KnownFolders.PicturesLibrary, fileNameNoEx + result.FileType, NameCollisionOption.GenerateUniqueName);

                    aPath = copy.Path;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("unable to save to album:" + ex);
                }
            }

            var file = await result.CopyAsync(folder, filename, NameCollisionOption.GenerateUniqueName).AsTask();

            return(new MediaFile(file.Path, () => file.OpenStreamForReadAsync().Result, albumPath: aPath));
        }
Пример #6
0
        /// <summary>
        ///  Rotate an image if required and saves it back to disk.
        /// </summary>
        /// <param name="filePath">The file image path</param>
        /// <param name="mediaOptions">The options.</param>
        /// <param name="exif">original metadata</param>
        /// <returns>True if rotation or compression occured, else false</returns>
        public Task <bool> FixOrientationAndResizeAsync(string filePath, StoreCameraMediaOptions mediaOptions, ExifInterface exif)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return(Task.FromResult(false));
            }

            try
            {
                return(Task.Run(() =>
                {
                    try
                    {
                        var rotation = GetRotation(exif);

                        // if we don't need to rotate, aren't resizing, and aren't adjusting quality then simply return
                        if (rotation == 0 && mediaOptions.PhotoSize == PhotoSize.Full && mediaOptions.CompressionQuality == 100)
                        {
                            return false;
                        }

                        var percent = 1.0f;
                        switch (mediaOptions.PhotoSize)
                        {
                        case PhotoSize.Large:
                            percent = .75f;
                            break;

                        case PhotoSize.Medium:
                            percent = .5f;
                            break;

                        case PhotoSize.Small:
                            percent = .25f;
                            break;

                        case PhotoSize.Custom:
                            percent = (float)mediaOptions.CustomPhotoSize / 100f;
                            break;
                        }

                        //First decode to just get dimensions
                        var options = new BitmapFactory.Options
                        {
                            InJustDecodeBounds = true
                        };

                        //already on background task
                        BitmapFactory.DecodeFile(filePath, options);

                        if (mediaOptions.PhotoSize == PhotoSize.MaxWidthHeight && mediaOptions.MaxWidthHeight.HasValue)
                        {
                            var max = Math.Max(options.OutWidth, options.OutHeight);
                            if (max > mediaOptions.MaxWidthHeight)
                            {
                                percent = (float)mediaOptions.MaxWidthHeight / (float)max;
                            }
                        }

                        var finalWidth = (int)(options.OutWidth * percent);
                        var finalHeight = (int)(options.OutHeight * percent);

                        //calculate sample size
                        options.InSampleSize = CalculateInSampleSize(options, finalWidth, finalHeight);

                        //turn off decode
                        options.InJustDecodeBounds = false;


                        //this now will return the requested width/height from file, so no longer need to scale
                        var originalImage = BitmapFactory.DecodeFile(filePath, options);

                        if (originalImage == null)
                        {
                            return false;
                        }

                        if (finalWidth != originalImage.Width || finalHeight != originalImage.Height)
                        {
                            originalImage = Bitmap.CreateScaledBitmap(originalImage, finalWidth, finalHeight, true);
                        }
                        if (rotation % 180 == 90)
                        {
                            var a = finalWidth;
                            finalWidth = finalHeight;
                            finalHeight = a;
                        }

                        //set scaled and rotated image dimensions
                        exif?.SetAttribute(pixelXDimens, Java.Lang.Integer.ToString(finalWidth));
                        exif?.SetAttribute(pixelYDimens, Java.Lang.Integer.ToString(finalHeight));

                        //if we need to rotate then go for it.
                        //then compresse it if needed
                        var photoType = System.IO.Path.GetExtension(filePath)?.ToLower();
                        var compressFormat = photoType == ".png" ? Bitmap.CompressFormat.Png : Bitmap.CompressFormat.Jpeg;
                        if (rotation != 0)
                        {
                            var matrix = new Matrix();
                            matrix.PostRotate(rotation);
                            using (var rotatedImage = Bitmap.CreateBitmap(originalImage, 0, 0, originalImage.Width, originalImage.Height, matrix, true))
                            {
                                //always need to compress to save back to disk
                                using (var stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                                {
                                    rotatedImage.Compress(compressFormat, mediaOptions.CompressionQuality, stream);
                                    stream.Close();
                                }
                                rotatedImage.Recycle();
                            }
                            //change the orienation to "not rotated"
                            exif?.SetAttribute(ExifInterface.TagOrientation, Java.Lang.Integer.ToString((int)Orientation.Normal));
                        }
                        else
                        {
                            //always need to compress to save back to disk
                            using (var stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                            {
                                originalImage.Compress(compressFormat, mediaOptions.CompressionQuality, stream);
                                stream.Close();
                            }
                        }

                        originalImage.Recycle();
                        originalImage.Dispose();
                        // Dispose of the Java side bitmap.
                        GC.Collect();
                        return true;
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        throw ex;
#else
                        return false;
#endif
                    }
                }));
            }
            catch (Exception ex)
            {
#if DEBUG
                throw ex;
#else
                return(Task.FromResult(false));
#endif
            }
        }
Пример #7
0
        public void OnClick(View v)
        {
            switch (v.Id)
            {
            case Resource.Id.addExpenseDelete:
                if (CurrentExpense != null && CurrentExpense.Id != -1)
                {
                    DeleteExpense();
                }
                else
                {
                    Dismiss();
                }
                break;

            case Resource.Id.addExpenseSave:
                SaveExpense();
                break;

            case Resource.Id.addExpenseCancel:
                Dismiss();
                break;

            case Resource.Id.addExpenseAddPhoto: {
                var choices = new List <string> ();
                choices.Add(activity.Resources.GetString(Resource.String.Gallery));
                if (mediaPicker.IsCameraAvailable)
                {
                    choices.Add(activity.Resources.GetString(Resource.String.Camera));
                }
                AlertDialog.Builder takePictureDialog = new AlertDialog.Builder(activity);
                takePictureDialog.SetTitle("Select:");
                takePictureDialog.SetItems(choices.ToArray(), (innerSender, innerE) => {
                        if (innerE.Which == 0)
                        {
                            //gallery
                            mediaPicker.PickPhotoAsync().ContinueWith(t => {
                                if (t.IsCanceled)
                                {
                                    return;
                                }
                                activity.RunOnUiThread(() => {
                                    expenseAddPhoto.Visibility = ViewStates.Gone;
                                    imageBitmap = BitmapFactory.DecodeStream(t.Result.GetStream());
                                    imageBitmap = Extensions.ResizeBitmap(imageBitmap, Constants.MaxWidth, Constants.MaxHeight);
                                    expensePhoto.SetImageBitmap(imageBitmap);
                                    expenseViewModel.Photo = new ExpensePhoto {
                                        ExpenseId = CurrentExpense.Id
                                    };
                                });
                            });
                        }
                        else if (innerE.Which == 1)
                        {
                            //camera
                            StoreCameraMediaOptions options = new StoreCameraMediaOptions();
                            options.Directory = "FieldService";
                            options.Name      = "FieldService.jpg";
                            mediaPicker.TakePhotoAsync(options).ContinueWith(t => {
                                if (t.IsCanceled)
                                {
                                    return;
                                }
                                activity.RunOnUiThread(() => {
                                    expenseAddPhoto.Visibility = ViewStates.Gone;
                                    imageBitmap = BitmapFactory.DecodeStream(t.Result.GetStream());
                                    imageBitmap = Extensions.ResizeBitmap(imageBitmap, Constants.MaxWidth, Constants.MaxHeight);
                                    expensePhoto.SetImageBitmap(imageBitmap);
                                    expenseViewModel.Photo = new ExpensePhoto {
                                        ExpenseId = CurrentExpense.Id
                                    };
                                });
                            });
                        }
                    });
                takePictureDialog.Show();
            }
            break;

            default:
                break;
            }
        }
        private Task <MediaFile> GetMediaAsync(UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
        {
            UIViewController viewController = null;
            UIWindow         window         = UIApplication.SharedApplication.KeyWindow;

            if (window == null)
            {
                throw new InvalidOperationException("There's no current active window");
            }

            if (window.WindowLevel == UIWindowLevel.Normal)
            {
                viewController = window.RootViewController;
            }

            if (viewController == null)
            {
                window = UIApplication.SharedApplication.Windows.OrderByDescending(w => w.WindowLevel).FirstOrDefault(w => w.RootViewController != null && w.WindowLevel == UIWindowLevel.Normal);
                if (window == null)
                {
                    throw new InvalidOperationException("Could not find current view controller");
                }
                else
                {
                    viewController = window.RootViewController;
                }
            }

            while (viewController.PresentedViewController != null)
            {
                viewController = viewController.PresentedViewController;
            }

            MediaPickerDelegate ndelegate = new MediaPickerDelegate(viewController, sourceType, options);
            var od = Interlocked.CompareExchange(ref pickerDelegate, ndelegate, null);

            if (od != null)
            {
                throw new InvalidOperationException("Only one operation can be active at at time");
            }

            var picker = SetupController(ndelegate, sourceType, mediaType, options);

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
            {
                ndelegate.Popover          = new UIPopoverController(picker);
                ndelegate.Popover.Delegate = new MediaPickerPopoverDelegate(ndelegate, picker);
                ndelegate.DisplayPopover();
            }
            else
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
                {
                    picker.ModalPresentationStyle = UIModalPresentationStyle.OverCurrentContext;
                }
                viewController.PresentViewController(picker, true, null);
            }

            return(ndelegate.Task.ContinueWith(t =>
            {
                if (popover != null)
                {
                    popover.Dispose();
                    popover = null;
                }

                Interlocked.Exchange(ref pickerDelegate, null);
                return t;
            }).Unwrap());
        }
Пример #9
0
        private static MediaPickerController SetupController(MediaPickerDelegate mpDelegate, UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
        {
            var picker = new MediaPickerController(mpDelegate)
            {
                MediaTypes = new[] { mediaType },
                SourceType = sourceType
            };

            if (sourceType != UIImagePickerControllerSourceType.Camera)
            {
                return(picker);
            }

            picker.CameraDevice  = GetUiCameraDevice(options.DefaultCamera);
            picker.AllowsEditing = options?.AllowCropping ?? false;

            var overlay = options.OverlayViewProvider?.Invoke();

            if (overlay is UIView)
            {
                picker.CameraOverlayView = overlay as UIView;
            }
            switch (mediaType)
            {
            case TypeImage:
                picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
                break;

            case TypeMovie:
                var voptions = (StoreVideoOptions)options;

                picker.CameraCaptureMode    = UIImagePickerControllerCameraCaptureMode.Video;
                picker.VideoQuality         = GetQuailty(voptions.Quality);
                picker.VideoMaximumDuration = voptions.DesiredLength.TotalSeconds;
                break;
            }

            return(picker);
        }
Пример #10
0
        private async void BtnFoto_Clicked(object sender, EventArgs e)
        {
            var opAlma = new StoreCameraMediaOptions()
            {
                Directory          = "Test",
                SaveToAlbum        = true,
                CompressionQuality = 75,
                CustomPhotoSize    = 50,
                PhotoSize          = PhotoSize.MaxWidthHeight,
                MaxWidthHeight     = 2000,
                DefaultCamera      = CameraDevice.Front,
                Name = "MiFoto.jpg",
            };

            var foto = await CrossMedia.Current.TakePhotoAsync(opAlma);

            miFoto.Source = ImageSource.FromStream(() =>
            {
                var stream = foto.GetStream();
                imgFoto    = foto.Path;
                foto.Dispose();
                return(stream);
            });



            //ubicacion real de la foto

            var locator = CrossGeolocator.Current;

            locator.DesiredAccuracy = 50;

            TimeSpan t1 = TimeSpan.FromSeconds(5);
            double   t2 = Convert.ToDouble(3000);

            var position = await locator.GetPositionAsync(10000);

            double latitud  = 0;
            double longitud = 0;

            if (locator.IsGeolocationAvailable)
            {
                if (locator.IsGeolocationEnabled)
                {
                    if (!locator.IsListening)
                    {
                        await locator.StartListeningAsync(5, t2);
                    }
                    locator.PositionChanged += (cambio, args) =>
                    {
                        var loc = args.Position;
                        latitud  = position.Latitude;
                        longitud = position.Longitude;
                    };
                }
            }
            var geoCoderPosition = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
            var geocoder         = new Geocoder();
            var addresses        = await geocoder.GetAddressesForPositionAsync(geoCoderPosition);

            string stCalle   = "";
            string stNumero  = "";
            string numero    = "";
            string cadenaCYN = "";

            foreach (var address in addresses)
            {
                String   cadena       = address.ToString().Replace("/", "/n");
                string[] separada     = cadena.Split(',');
                string   cadenaAltura = separada[0];
                for (int i = 0; i < cadenaAltura.Length; i++)
                {
                    cadenaCYN = cadenaAltura.Substring(i, 1);
                    switch (cadenaCYN)
                    {
                    case "0":
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                    case "5":
                    case "6":
                    case "7":
                    case "8":
                    case "9": stNumero = stNumero + cadenaCYN; break;

                    default: stCalle = stCalle + cadenaCYN; break;
                    }
                }
                for (int i = 0; i < stNumero.Length; i++)
                {
                    numero = stNumero.Substring(i, 1);
                    if (numero == "-")
                    {
                        stNumero = stNumero + "-" + numero;
                    }
                }
                stCalleFoto = stCalle;
                stNroFoto   = stNumero;

                break;
            }
        }
#pragma warning disable CS1998 // 이 비동기 메서드에는 'await' 연산자가 없으며 메서드가 동시에 실행됩니다.
        public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options)
#pragma warning restore CS1998 // 이 비동기 메서드에는 'await' 연산자가 없으며 메서드가 동시에 실행됩니다.
        {
            return(null);
        }
Пример #12
0
        static void ResizeAndCompressImage(StoreCameraMediaOptions options, MediaFile mediaFile, string pathExtension)
        {
            var image   = UIImage.FromFile(mediaFile.Path);
            var percent = 1.0f;

            if (options.PhotoSize != PhotoSize.Full)
            {
                try
                {
                    switch (options.PhotoSize)
                    {
                    case PhotoSize.Large:
                        percent = .75f;
                        break;

                    case PhotoSize.Medium:
                        percent = .5f;
                        break;

                    case PhotoSize.Small:
                        percent = .25f;
                        break;

                    case PhotoSize.Custom:
                        percent = (float)options.CustomPhotoSize / 100f;
                        break;
                    }

                    if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue)
                    {
                        var max = Math.Max(image.Size.Width, image.Size.Height);
                        if (max > options.MaxWidthHeight.Value)
                        {
                            percent = (float)options.MaxWidthHeight.Value / (float)max;
                        }
                    }

                    if (percent < 1.0f)
                    {
                        //begin resizing image
                        image = image.ResizeImageWithAspectRatio(percent);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to compress image: {ex}");
                }
            }
            NSDictionary meta = null;

            if (options.SaveMetaData)
            {
                try
                {
                    meta = PhotoLibraryAccess.GetPhotoLibraryMetadata(new NSUrl(mediaFile.AlbumPath));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to get metadata: {ex}");
                }
            }
            //iOS quality is 0.0-1.0
            var quality    = (options.CompressionQuality / 100f);
            var savedImage = false;

            if (meta != null)
            {
                savedImage = MediaPickerDelegate.SaveImageWithMetadata(image, quality, meta, mediaFile.Path, pathExtension);
            }

            if (!savedImage)
            {
                if (pathExtension == "png")
                {
                    image.AsPNG().Save(mediaFile.Path, true);
                }
                else
                {
                    image.AsJPEG(quality).Save(mediaFile.Path, true);
                }
            }

            image?.Dispose();
            image = null;
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        }
Пример #13
0
        private async void TakePhoto()
        {
            try
            {
                int userid = (int)Preferences.Get("UserID", 0);

                var mediaOptions = new StoreCameraMediaOptions()
                {
                    SaveToAlbum        = false,
                    Directory          = "Sample",
                    Name               = userid + "_photo.jpg",
                    PhotoSize          = PhotoSize.Small,
                    DefaultCamera      = Plugin.Media.Abstractions.CameraDevice.Front,
                    RotateImage        = false,
                    CompressionQuality = 50,
                    AllowCropping      = true,
                    SaveMetaData       = false,
                    CustomPhotoSize    = 70 //Resize to 90% of original
                };

                if (!CrossMedia.Current.IsTakePhotoSupported)
                {
                    return;
                }
                var selectedImageFile = await CrossMedia.Current.TakePhotoAsync(mediaOptions);

                if (selectedImageFile != null)
                {
                    try
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            selectedImageFile.GetStreamWithImageRotatedForExternalStorage();


                            //var signatureMemoryStream = memoryStream.ToArray();
                            //Photo = signatureMemoryStream;
                            await UserService.UploadPhoto(selectedImageFile.GetStreamWithImageRotatedForExternalStorage(), userid.ToString() + ".jpg");

                            PhotoURL = ImageSource.FromFile(selectedImageFile.Path);
                            // = EndPoint.BACKEND_ENDPOINT + "/uploads/" + userid.ToString() + ".jpg";
                            Preferences.Set("MyFoto", selectedImageFile.Path);
                            selectedImageFile.Dispose();
                        }
                    }
                    catch (Exception)
                    {
                        await Application.Current.MainPage.DisplayAlert("Job Me", "Ocurrio un error al actualizar la foto", "Ok");

                        // throw;
                    }

                    return;
                }
                ;
            }
            catch (Exception)
            {
                await Application.Current.MainPage.DisplayAlert("Job Me", "Ocurrio un error al actualizar la foto", "Ok");

                //throw;
            }
        }
Пример #14
0
        protected override async void OnResume()
        {
            base.OnResume();

            int itemId = Intent.GetIntExtra(ShareItemIdExtraName, 0);

            if (itemId > 0)
            {
                shareItem = App.Database.GetItem(itemId);

                fileName = shareItem.ImagePath;
                System.Console.WriteLine("Image path: " + fileName);
                Bitmap b = BitmapFactory.DecodeFile(fileName);
                // Display the bitmap
                photoImageView.SetImageBitmap(b);
                locationText.Text = shareItem.Location;
                return;
            }

            if (fileName == "")
            {
                fileName = "in-progress";
                var picker = new MediaPicker(this);
                //           new MediaPicker (); on iOS
                if (!picker.IsCameraAvailable)
                {
                    System.Console.WriteLine("No camera!");
                }
                else
                {
                    var options = new StoreCameraMediaOptions {
                        Name      = DateTime.Now.ToString("yyyyMMddHHmmss"),
                        Directory = "MediaPickerSample"
                    };

                    if (!picker.IsCameraAvailable || !picker.PhotosSupported)
                    {
                        ShowUnsupported();
                        return;
                    }

                    Intent intent = picker.GetTakePhotoUI(options);

                    StartActivityForResult(intent, 1);
                }
            }
            else
            {
                SetImage();
            }

            try {
                var locator = new Geolocator(this)
                {
                    DesiredAccuracy = 50
                };
                //            new Geolocator () { ... }; on iOS
                var position = await locator.GetPositionAsync(timeout : 10000);

                System.Console.WriteLine("Position Latitude: {0}", position.Latitude);
                System.Console.WriteLine("Position Longitude: {0}", position.Longitude);

                location          = string.Format("{0},{1}", position.Latitude, position.Longitude);
                locationText.Text = location;
            } catch (Exception e) {
                System.Console.WriteLine("Position Exception: " + e.Message);
            }
        }
Пример #15
0
        /// <summary>
        ///  Rotate an image if required and saves it back to disk.
        /// </summary>
        /// <param name="filePath">The file image path</param>
        /// <param name="mediaOptions">The options.</param>
        /// <returns>True if rotation or compression occured, else false</returns>
        ///
        public Task <bool> FixOrientationAndResizeAsync(string filePath, StoreCameraMediaOptions mediaOptions)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return(Task.FromResult(false));
            }

            try {
                return(Task.Run(() => {
                    try {
                        //First decode to just get dimensions
                        var options = new BitmapFactory.Options {
                            InJustDecodeBounds = true
                        };

                        //already on background task
                        BitmapFactory.DecodeFile(filePath, options);

                        var rotation = GetRotation(filePath);

                        if (rotation == 0 && mediaOptions.PhotoSize == PhotoSize.Full)
                        {
                            return false;
                        }

                        var percent = 1.0f;
                        switch (mediaOptions.PhotoSize)
                        {
                        case PhotoSize.Large:
                            percent = .75f;
                            break;

                        case PhotoSize.Medium:
                            percent = .5f;
                            break;

                        case PhotoSize.Small:
                            percent = .25f;
                            break;

                        case PhotoSize.Custom:
                            percent = (float)mediaOptions.CustomPhotoSize / 100f;
                            break;
                        }
                        if (mediaOptions.PhotoSize == PhotoSize.Manual && mediaOptions.ManualSize.HasValue)
                        {
                            var max = Math.Max(options.OutWidth, options.OutHeight);
                            if (max > mediaOptions.ManualSize)
                            {
                                percent = (float)mediaOptions.ManualSize / (float)max;
                            }
                        }
                        var finalWidth = (int)(options.OutWidth * percent);
                        var finalHeight = (int)(options.OutHeight * percent);

                        //calculate sample size
                        options.InSampleSize = CalculateInSampleSize(options, finalWidth, finalHeight);

                        //turn off decode
                        options.InJustDecodeBounds = false;


                        //this now will return the requested width/height from file, so no longer need to scale
                        var originalImage = BitmapFactory.DecodeFile(filePath, options);

                        if (finalWidth != originalImage.Width || finalHeight != originalImage.Height)
                        {
                            originalImage = Bitmap.CreateScaledBitmap(originalImage, finalWidth, finalHeight, true);
                        }
                        //if we need to rotate then go for it.
                        //then compresse it if needed
                        if (rotation != 0)
                        {
                            var matrix = new Matrix();
                            matrix.PostRotate(rotation);
                            using (var rotatedImage = Bitmap.CreateBitmap(originalImage, 0, 0, originalImage.Width, originalImage.Height, matrix, true)) {
                                //always need to compress to save back to disk
                                using (var stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite)) {
                                    rotatedImage.Compress(Bitmap.CompressFormat.Jpeg, mediaOptions.CompressionQuality, stream);
                                    stream.Close();
                                }
                                rotatedImage.Recycle();
                            }
                            originalImage.Recycle();
                            originalImage.Dispose();
                            // Dispose of the Java side bitmap.
                            GC.Collect();
                            return true;
                        }



                        //always need to compress to save back to disk
                        using (var stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite)) {
                            originalImage.Compress(Bitmap.CompressFormat.Jpeg, mediaOptions.CompressionQuality, stream);
                            stream.Close();
                        }



                        originalImage.Recycle();
                        originalImage.Dispose();
                        // Dispose of the Java side bitmap.
                        GC.Collect();
                        return true;
                    } catch (Exception ex) {
#if DEBUG
                        throw ex;
#else
                        return false;
#endif
                    }
                }));
            } catch (Exception ex) {
#if DEBUG
                throw ex;
#else
                return(Task.FromResult(false));
#endif
            }
        }
        private static MediaPickerController SetupController(MediaPickerDelegate mpDelegate, UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
        {
            var picker = new MediaPickerController(mpDelegate);

            picker.MediaTypes = new[] { mediaType };
            picker.SourceType = sourceType;

            if (sourceType == UIImagePickerControllerSourceType.Camera)
            {
                picker.CameraDevice  = GetUICameraDevice(options.DefaultCamera);
                picker.AllowsEditing = options?.AllowCropping ?? false;

                if (options.OverlayViewProvider != null)
                {
                    var overlay = options.OverlayViewProvider();
                    if (overlay is UIView)
                    {
                        picker.CameraOverlayView = overlay as UIView;
                    }
                }
                if (mediaType == TypeImage)
                {
                    picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
                }
                else if (mediaType == TypeMovie)
                {
                    StoreVideoOptions voptions = (StoreVideoOptions)options;

                    picker.CameraCaptureMode    = UIImagePickerControllerCameraCaptureMode.Video;
                    picker.VideoQuality         = GetQuailty(voptions.Quality);
                    picker.VideoMaximumDuration = voptions.DesiredLength.TotalSeconds;
                }
            }

            return(picker);
        }
Пример #17
0
        private Task <MediaFile> GetMediaAsync(UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null, CancellationToken token = default(CancellationToken))
        {
            var viewController = GetHostViewController();

            if (token.IsCancellationRequested)
            {
                return(Task.FromResult((MediaFile)null));
            }

            var ndelegate = new MediaPickerDelegate(viewController, sourceType, options, token);
            var od        = Interlocked.CompareExchange(ref pickerDelegate, ndelegate, null);

            if (od != null)
            {
                throw new InvalidOperationException("Only one operation can be active at a time");
            }

            var picker = SetupController(ndelegate, sourceType, mediaType, options);

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
            {
                ndelegate.Popover          = popover = new UIPopoverController(picker);
                ndelegate.Popover.Delegate = new MediaPickerPopoverDelegate(ndelegate, picker);
                ndelegate.DisplayPopover();

                token.Register(() =>
                {
                    if (popover == null)
                    {
                        return;
                    }
                    NSRunLoop.Main.BeginInvokeOnMainThread(() =>
                    {
                        ndelegate.Popover.Dismiss(true);
                        ndelegate.CancelTask();
                    });
                });
            }
            else
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
                {
                    picker.ModalPresentationStyle = options?.ModalPresentationStyle == MediaPickerModalPresentationStyle.OverFullScreen
                                ? UIModalPresentationStyle.OverFullScreen
                                : UIModalPresentationStyle.FullScreen;
                }
                viewController.PresentViewController(picker, true, null);

                token.Register(() =>
                {
                    if (picker == null)
                    {
                        return;
                    }

                    NSRunLoop.Main.BeginInvokeOnMainThread(() =>
                    {
                        picker.DismissModalViewController(true);
                        ndelegate.CancelTask();
                    });
                });
            }

            return(ndelegate.Task.ContinueWith(t =>
            {
                Dismiss(popover, picker);

                return t.Result == null ? null : t.Result.FirstOrDefault();
            }));
        }
Пример #18
0
 ELCImagePickerViewController(UIViewController rootController, StoreCameraMediaOptions options = null) : base(rootController)
 {
     this.options = options ?? new StoreCameraMediaOptions();
 }
Пример #19
0
        private Task <List <MediaFile> > GetMediasAsync(UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null, MultiPickerOptions pickerOptions = null, CancellationToken token = default(CancellationToken))
        {
            var viewController = GetHostViewController();

            if (options == null)
            {
                options = new StoreCameraMediaOptions();
            }

            var ndelegate = new MediaPickerDelegate(viewController, sourceType, options, token);
            var od        = Interlocked.CompareExchange(ref pickerDelegate, ndelegate, null);

            if (od != null)
            {
                throw new InvalidOperationException("Only one operation can be active at a time");
            }

            var picker = ELCImagePickerViewController.Create(options, pickerOptions);

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
            {
                ndelegate.Popover          = popover = new UIPopoverController(picker);
                ndelegate.Popover.Delegate = new MediaPickerPopoverDelegate(ndelegate, picker);
                ndelegate.DisplayPopover();
            }
            else
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
                {
                    picker.ModalPresentationStyle = UIModalPresentationStyle.OverCurrentContext;
                }
                viewController.PresentViewController(picker, true, null);
            }

            // TODO: Make this use the existing Delegate?
            return(picker.Completion.ContinueWith(t =>
            {
                Dismiss(popover, picker);
                picker.BeginInvokeOnMainThread(() =>
                {
                    picker.DismissViewController(true, null);
                });

                if (t.IsCanceled || t.Exception != null)
                {
                    return Task.FromResult(new List <MediaFile>());
                }

                var files = t.Result;
                Parallel.ForEach(files, mediaFile =>
                {
                    ResizeAndCompressImage(options, mediaFile, Path.GetExtension(mediaFile.Path));
                });

                return t;
            }).Unwrap());
        }
Пример #20
0
        /// <summary>
        /// Take a photo async with specified options
        /// </summary>
        /// <param name="options">Camera Media Options</param>
        /// <param name="token">Cancellation token</param>
        /// <returns>Media file of photo or null if canceled</returns>
        public async Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options, CancellationToken token = default(CancellationToken))
        {
            if (!IsCameraAvailable)
            {
                throw new NotSupportedException();
            }

            if (!(await RequestCameraPermissions()))
            {
                throw new MediaPermissionException(nameof(Permissions.Camera));
            }

            VerifyOptions(options);

            var media = await TakeMediaAsync("image/*", MediaStore.ActionImageCapture, options, token);

            if (string.IsNullOrWhiteSpace(media?.Path))
            {
                return(media);
            }

            if (options.SaveToAlbum)
            {
                var fileName = System.IO.Path.GetFileName(media.Path);
                var uri      = MediaPickerActivity.GetOutputMediaFile(context, options.Directory ?? "temp", fileName, true, true);
                var f        = new Java.IO.File(uri.Path);
                media.AlbumPath = uri.ToString();

                try
                {
                    var values = new ContentValues();
                    values.Put(MediaStore.Audio.Media.InterfaceConsts.DisplayName, System.IO.Path.GetFileNameWithoutExtension(f.AbsolutePath));
                    values.Put(MediaStore.Audio.Media.InterfaceConsts.MimeType, "image/jpeg");
                    values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty);
                    values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
                    values.Put(MediaStore.Images.ImageColumns.BucketId, f.ToString().ToLowerInvariant().GetHashCode());
                    values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, f.Name.ToLowerInvariant());

                    var cr       = context.ContentResolver;
                    var albumUri = cr.Insert(MediaStore.Images.Media.ExternalContentUri, values);

                    using (System.IO.Stream input = File.OpenRead(media.Path))
                        using (System.IO.Stream output = cr.OpenOutputStream(albumUri))
                            input.CopyTo(output);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to save to gallery: " + ex);
                }
            }

            //check to see if we need to rotate if success
            try
            {
                var exif = new ExifInterface(media.Path);
                if (options.RotateImage)
                {
                    await FixOrientationAndResizeAsync(media.Path, options, exif);
                }
                else
                {
                    await ResizeAsync(media.Path, options, exif);
                }

                if (options.SaveMetaData && IsValidExif(exif))
                {
                    SetMissingMetadata(exif, options.Location);

                    try
                    {
                        exif?.SaveAttributes();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Unable to save exif {ex}");
                    }
                }

                exif?.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to check orientation: " + ex);
            }

            return(media);
        }
Пример #21
0
        private static void ResizeAndCompressImage(StoreCameraMediaOptions options, MediaFile mediaFile, string pathExtension)
        {
            var image   = UIImage.FromFile(mediaFile.Path);
            var percent = 1.0f;

            if (options.PhotoSize != PhotoSize.Full)
            {
                try
                {
                    switch (options.PhotoSize)
                    {
                    case PhotoSize.Large:
                        percent = .75f;
                        break;

                    case PhotoSize.Medium:
                        percent = .5f;
                        break;

                    case PhotoSize.Small:
                        percent = .25f;
                        break;

                    case PhotoSize.Custom:
                        percent = (float)options.CustomPhotoSize / 100f;
                        break;
                    }

                    if (options.PhotoSize == PhotoSize.MaxWidthHeight && options.MaxWidthHeight.HasValue)
                    {
                        var max = Math.Max(image.Size.Width, image.Size.Height);
                        if (max > options.MaxWidthHeight.Value)
                        {
                            percent = (float)options.MaxWidthHeight.Value / (float)max;
                        }
                    }

                    if (percent < 1.0f)
                    {
                        //begin resizing image
                        image = image.ResizeImageWithAspectRatio(percent);
                    }

                    NSDictionary meta = null;
                    try
                    {
                        //meta = PhotoLibraryAccess.GetPhotoLibraryMetadata(asset.AssetUrl);

                        //meta = info[UIImagePickerController.MediaMetadata] as NSDictionary;
                        if (meta != null && meta.ContainsKey(ImageIO.CGImageProperties.Orientation))
                        {
                            var newMeta = new NSMutableDictionary();
                            newMeta.SetValuesForKeysWithDictionary(meta);
                            var newTiffDict = new NSMutableDictionary();
                            newTiffDict.SetValuesForKeysWithDictionary(meta[ImageIO.CGImageProperties.TIFFDictionary] as NSDictionary);
                            newTiffDict.SetValueForKey(meta[ImageIO.CGImageProperties.Orientation], ImageIO.CGImageProperties.TIFFOrientation);
                            newMeta[ImageIO.CGImageProperties.TIFFDictionary] = newTiffDict;

                            meta = newMeta;
                        }
                        var location = options.Location;
                        if (meta != null && location != null)
                        {
                            meta = MediaPickerDelegate.SetGpsLocation(meta, location);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Unable to get metadata: {ex}");
                    }

                    //iOS quality is 0.0-1.0
                    var quality    = (options.CompressionQuality / 100f);
                    var savedImage = false;
                    if (meta != null)
                    {
                        savedImage = MediaPickerDelegate.SaveImageWithMetadata(image, quality, meta, mediaFile.Path, pathExtension);
                    }

                    if (!savedImage)
                    {
                        image.AsJPEG(quality).Save(mediaFile.Path, true);
                    }

                    image?.Dispose();
                    image = null;

                    GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Unable to compress image: {ex}");
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Resize Image Async
        /// </summary>
        /// <param name="filePath">The file image path</param>
        /// <param name="photoSize">Photo size to go to.</param>
        /// <param name="quality">Image quality (1-100)</param>
        /// <param name="customPhotoSize">Custom size in percent</param>
        /// <param name="exif">original metadata</param>
        /// <returns>True if rotation or compression occured, else false</returns>
        public Task <bool> ResizeAsync(string filePath, StoreCameraMediaOptions mediaOptions, ExifInterface exif)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return(Task.FromResult(false));
            }

            try
            {
                var photoSize       = mediaOptions.PhotoSize;
                var customPhotoSize = mediaOptions.CustomPhotoSize;
                var quality         = mediaOptions.CompressionQuality;
                return(Task.Run(() =>
                {
                    try
                    {
                        if (photoSize == PhotoSize.Full)
                        {
                            return false;
                        }

                        var percent = 1.0f;
                        switch (photoSize)
                        {
                        case PhotoSize.Large:
                            percent = .75f;
                            break;

                        case PhotoSize.Medium:
                            percent = .5f;
                            break;

                        case PhotoSize.Small:
                            percent = .25f;
                            break;

                        case PhotoSize.Custom:
                            percent = (float)customPhotoSize / 100f;
                            break;
                        }


                        //First decode to just get dimensions
                        var options = new BitmapFactory.Options
                        {
                            InJustDecodeBounds = true
                        };

                        //already on background task
                        BitmapFactory.DecodeFile(filePath, options);

                        if (mediaOptions.PhotoSize == PhotoSize.MaxWidthHeight && mediaOptions.MaxWidthHeight.HasValue)
                        {
                            var max = Math.Max(options.OutWidth, options.OutHeight);
                            if (max > mediaOptions.MaxWidthHeight)
                            {
                                percent = (float)mediaOptions.MaxWidthHeight / (float)max;
                            }
                        }

                        var finalWidth = (int)(options.OutWidth * percent);
                        var finalHeight = (int)(options.OutHeight * percent);

                        //set scaled image dimensions
                        exif?.SetAttribute(pixelXDimens, Java.Lang.Integer.ToString(finalWidth));
                        exif?.SetAttribute(pixelYDimens, Java.Lang.Integer.ToString(finalHeight));

                        //calculate sample size
                        options.InSampleSize = CalculateInSampleSize(options, finalWidth, finalHeight);

                        //turn off decode
                        options.InJustDecodeBounds = false;


                        //this now will return the requested width/height from file, so no longer need to scale
                        using (var originalImage = BitmapFactory.DecodeFile(filePath, options))
                        {
                            //always need to compress to save back to disk
                            using (var stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                            {
                                originalImage.Compress(Bitmap.CompressFormat.Jpeg, quality, stream);
                                stream.Close();
                            }

                            originalImage.Recycle();

                            // Dispose of the Java side bitmap.
                            GC.Collect();
                            return true;
                        }
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        throw ex;
#else
                        return false;
#endif
                    }
                }));
            }
            catch (Exception ex)
            {
#if DEBUG
                throw ex;
#else
                return(Task.FromResult(false));
#endif
            }
        }
Пример #23
0
        // Evento que abre a câmera para fotografar o Teste
        private async void BtnTeste_ClickedAsync(object sender, EventArgs e)
        {
            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);

                if (status != PermissionStatus.Granted)
                {
                    if (!await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Camera))
                    {
                        await DisplayAlert("Permissão", "Permita o acesso à câmera.", "OK");

                        CrossPermissions.Current.OpenAppSettings();
                    }

                    var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Camera });

                    status = results[Permission.Camera];
                }

                if (status == PermissionStatus.Granted)
                {
                    await CrossMedia.Current.Initialize();

                    if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
                    {
                        await DisplayAlert("Nenhuma Câmera", "Nenuma Câmera disponível.", "Fechar");

                        return;
                    }

                    var armazenamento = new StoreCameraMediaOptions()
                    {
                        SaveToAlbum        = true,
                        Name               = "photoTest.jpg",
                        PhotoSize          = PhotoSize.Small,
                        CompressionQuality = 50
                    };

                    var foto = await CrossMedia.Current.TakePhotoAsync(armazenamento);

                    if (foto == null)
                    {
                        return;
                    }

                    DigitalizarTesteViewModel.Fotografado = true;

                    Stream       stm = foto.GetStream();
                    MemoryStream ms  = new MemoryStream();

                    stm.CopyTo(ms);
                    TesteImagemViewModel = new TesteImagemViewModel {
                        Imagem = ms.ToArray()
                    };

                    imgFoto.Source = ImageSource.FromStream(() =>
                    {
                        var stream = foto.GetStream();
                        foto.Dispose();
                        return(stream);
                    });

                    BtnEnviarTeste.IsEnabled = true;
                    btnTeste.Text            = "Fotografar novamente";
                }

                else if (status != PermissionStatus.Unknown)
                {
                    await DisplayAlert("Permissões", "Não foi possível continuar, tente novamente.", "OK");
                }
            }

            catch (Exception ex)
            {
                await DisplayAlert("Erro", "Câmera indisponível.", "OK");

                await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Storage);
            }
        }
Пример #24
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="options"></param>
 /// <returns></returns>
 public Task <MediaFile> TakePhotoAsync(StoreCameraMediaOptions options)
 {
     return(Task.FromResult <MediaFile>(null));
 }
Пример #25
0
        public override async void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = "in-progress";
                var picker = new MediaPicker();
                if (!picker.IsCameraAvailable || !picker.PhotosSupported)
                {
                    Console.WriteLine("No camera!");
                }
                else
                {
                    var options = new StoreCameraMediaOptions {
                        Name      = DateTime.Now.ToString("yyyyMMddHHmmss"),
                        Directory = "MediaPickerSample"
                    };

                    pickerController = picker.GetTakePhotoUI(options);
                    PresentViewController(pickerController, true, null);

                    MediaFile media;

                    try {
                        var   pickerTask = pickerController.GetResultAsync();
                        await pickerTask;

                        // User canceled or something went wrong
                        if (pickerTask.IsCanceled || pickerTask.IsFaulted)
                        {
                            fileName = string.Empty;
                            return;
                        }

                        media    = pickerTask.Result;
                        fileName = media.Path;

                        // We need to dismiss the controller ourselves
                        await DismissViewControllerAsync(true);                          // woot! async-ified iOS method
                    }
                    catch (AggregateException ae) {
                        fileName = string.Empty;
                        Console.WriteLine("Error while huh: {0}", ae.Message);
                    } catch (Exception e) {
                        fileName = string.Empty;
                        Console.WriteLine("Error while cancelling: {0}", e.Message);
                    }

                    if (String.IsNullOrEmpty(fileName))
                    {
                        await DismissViewControllerAsync(true);
                    }
                    else
                    {
                        PhotoImageView.Image = new UIImage(fileName);
                        SavePicture(fileName);
                    }
                }
            }
            else if (fileName == "cancelled")
            {
                NavigationController.PopToRootViewController(true);
            }
            else
            {
                // populate screen with existing item
                PhotoImageView.Image = FileExists(fileName) ? new UIImage(fileName) : null;
                LocationText.Text    = location;
            }

            var locator = new Geolocator {
                DesiredAccuracy = 50
            };
            var position = await locator.GetPositionAsync(new CancellationToken(), false);

            Console.WriteLine("Position Latitude: {0}", position.Latitude);
            Console.WriteLine("Position Longitude: {0}", position.Longitude);

            location = string.Format("{0},{1}", position.Latitude, position.Longitude);

            LocationText.Text = location;
        }
 public static ELCImagePickerViewController Create(StoreCameraMediaOptions options = null, MultiPickerOptions pickerOptions = null)
 {
     pickerOptions = pickerOptions ?? new MultiPickerOptions();
     return(Create(options, pickerOptions.MaximumImagesCount, pickerOptions.AlbumSelectTitle, pickerOptions.PhotoSelectTitle, pickerOptions.BackButtonTitle, null, pickerOptions.DoneButtonTitle, pickerOptions.LoadingTitle, pickerOptions.PathToOverlay));
 }
Пример #27
0
        private async Task SelectUserPictureActionAsync()
        {
            try
            {
                string imagePath = UserData.Instance.UserInfo == null ? null : AppTools.Instance.GetUserImageLocalPath(UserData.Instance.UserInfo.UserId);

                if (string.IsNullOrWhiteSpace(imagePath))
                {
                    return;
                }

                MediaFile mediaFile = null;
                await CrossMedia.Current.Initialize();

                if (await _userDialog.ConfirmAsync(Translation.Get(TRS.DO_YOU_WANT_TAKE_PHOTO_WITH_CAMERA_PI), Translation.Get(TRS.QUESTION), Translation.Get(TRS.YES), Translation.Get(TRS.NO)))
                {
                    // take a photo
                    if (!CrossMedia.Current.IsCameraAvailable)
                    {
                        await _userDialog.AlertAsync(string.Format(Translation.Get(TRS.P0_ISNT_SUPPORTED_ON_THIS_DEVICE), Translation.Get(TRS.TAKE_PHOTO)), Translation.Get(TRS.ERROR), Translation.Get(TRS.OK));

                        return;
                    }
                    StoreCameraMediaOptions cameraOption = new StoreCameraMediaOptions()
                    {
                        Directory   = "BodyReport",
                        Name        = "tempPhoto.jpg",
                        SaveToAlbum = true
                    };
                    mediaFile = await CrossMedia.Current.TakePhotoAsync(cameraOption);
                }
                else
                {
                    if (!CrossMedia.Current.IsTakePhotoSupported)
                    {
                        await _userDialog.AlertAsync(string.Format(Translation.Get(TRS.P0_ISNT_SUPPORTED_ON_THIS_DEVICE), Translation.Get(TRS.SELECT_PICTURE)), Translation.Get(TRS.ERROR), Translation.Get(TRS.OK));

                        return;
                    }
                    mediaFile = await CrossMedia.Current.PickPhotoAsync();
                }

                if (mediaFile == null || string.IsNullOrWhiteSpace(mediaFile.Path))
                {
                    return;
                }

                string pngImagePath = Path.Combine(AppTools.TempDirectory, UserData.Instance.UserInfo.UserId.ToString() + ".png");
                BodyReportMobile.Core.Framework.IMedia.Instance.CompressImageAsPng(mediaFile.Path, pngImagePath, 400);

                //Upload on server
                string uploadedRelativeUrl = await UserProfileWebService.UploadUserProfilePictureAsync(pngImagePath);

                if (string.IsNullOrWhiteSpace(uploadedRelativeUrl))
                {
                    _fileManager.DeleteFile(pngImagePath);
                    await _userDialog.AlertAsync(string.Format(Translation.Get(TRS.IMPOSSIBLE_TO_UPDATE_P0), Translation.Get(TRS.IMAGE)), Translation.Get(TRS.ERROR), Translation.Get(TRS.OK));
                }
                else //Copy file on local
                {
                    _fileManager.CopyFile(pngImagePath, imagePath);
                    _fileManager.DeleteFile(pngImagePath);
                    DisplayUserProfil();
                }
            }
            catch (Exception except)
            {
                ILogger.Instance.Error("Can't take user profile image", except);
            }
        }