Ejemplo n.º 1
0
        public override void OnTakePicturesComplete(MultiAssetEventArgs pictures)
        {
            if (pictures == null)
            {
                return;
            }
            ImagesAttach.Clear();
            ImagesToAddCount = pictures.Assets.Length;
            CallbacksCount   = 0;

            var imageManager = new PHImageManager();

            foreach (var asset in pictures.Assets)
            {
                imageManager.RequestImageData(asset,
                                              new PHImageRequestOptions {
                    DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat
                },
                                              (NSData data, NSString dataUti, UIImageOrientation orientation, NSDictionary info) =>
                {
                    double?latFinal = null;
                    double?lonFinal = null;
                    if (data != null)
                    {
                        GetLocationFromImageData(data, ref latFinal, ref lonFinal);
                    }

                    var picture = new CameraPicture {
                        Image = UIImage.LoadFromData(data), Data = data, Lat = latFinal, Lon = lonFinal
                    };
                    AddImagesIfRequired(picture);
                });
            }
        }
Ejemplo n.º 2
0
        void PickerController_FinishedPickingAssets(object sender, MultiAssetEventArgs args)
        {
            List <object> encodedImages = new List <object>();

            foreach (var asset in args.Assets)
            {
                PHImageManager imageManager = new PHImageManager();

                // we make sure the image are saved in the same quality with this option
                PHImageRequestOptions options = new PHImageRequestOptions {
                    NetworkAccessAllowed = true,
                    DeliveryMode         = PHImageRequestOptionsDeliveryMode.HighQualityFormat,
                    Synchronous          = true
                };
                imageManager.RequestImageForAsset(asset,
                                                  new CGSize(asset.PixelWidth, asset.PixelHeight), PHImageContentMode.Default, options,
                                                  (image, info) => {
                    byte[] dataBytes = new byte[image.AsPNG().Length];
                    System.Runtime.InteropServices.Marshal.Copy(image.AsPNG().Bytes, dataBytes, 0, Convert.ToInt32(image.AsPNG().Length));
                    encodedImages.Add(dataBytes);
                });
            }
            // post the message with the list attached
            MessagingCenter.Send <object, object>(this, MessagingKeys.DidFinishSelectingImages, encodedImages);
        }
        private async void SetGalleryButton()
        {
            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status == PHAuthorizationStatus.Authorized)
            {
                var options = new PHFetchOptions
                {
                    SortDescriptors = new[] { new NSSortDescriptor("creationDate", false) },
                    FetchLimit      = 5,
                };

                var fetchedAssets    = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
                var lastGalleryPhoto = fetchedAssets.FirstOrDefault() as PHAsset;
                if (lastGalleryPhoto != null)
                {
                    var PHImageManager = new PHImageManager();
                    PHImageManager.RequestImageForAsset(lastGalleryPhoto, new CGSize(300, 300),
                                                        PHImageContentMode.AspectFill, new PHImageRequestOptions(), (img, info) =>
                    {
                        galleryButton.Image = img;
                    });
                }
                else
                {
                    galleryButton.Image = UIImage.FromBundle("ic_noavatar");
                }
            }
        }
Ejemplo n.º 4
0
        private async Task <Stream> GetStreamPHAsync(string path)
        {
            Debug.WriteLine("MediaFile: GetStreamPH entered with path = {0}", (object)path);
            var streamCompletion = new TaskCompletionSource <Stream>();

            using (var assetUrl = new NSUrl(path))
            {
                using (var asset = GetAssetPH(assetUrl))
                {
                    var    imageDataTCS = new TaskCompletionSource <NSData>();
                    NSData imgData;
                    using (var manager = new PHImageManager())
                    {
                        manager.RequestImageData(
                            asset,
                            null,
                            (data, dataUti, orientation, info) =>
                        {
                            Debug.WriteLine("MediaFile: data is {0} bytes", data.Length);
                            imageDataTCS.SetResult(data);
                        });
                        Debug.WriteLine("MediaFile: waiting for imgData");
                        imgData = await imageDataTCS.Task.ConfigureAwait(false);
                    }
                    Debug.WriteLine("MediaFile: imgData is {0} bytes", imgData.Length);
                    streamCompletion.SetResult(imgData.AsStream());
                }
            }
            Debug.WriteLine("MediaFile: waiting for stream");
            var stream = await streamCompletion.Task;

            Debug.WriteLine("MediaFile: stream returned with length {0}", stream.Length);
            return(stream);
        }
Ejemplo n.º 5
0
        async void Picker_FinishedPickingAssets(object sender, MultiAssetEventArgs args)
        {
            PHImageManager imageManager = new PHImageManager();

            Console.WriteLine("User finished picking assets. {0} items selected.", args.Assets.Length);

            _preselectedAssets = args.Assets;

            // For demo purposes: just show all chosen pictures in order every second
            foreach (var asset in args.Assets)
            {
                imagePreview.Image = null;

                // Get information about the asset, e.g. file patch
                asset.RequestContentEditingInput(new PHContentEditingInputRequestOptions(),
                                                 (input, _) =>
                {
                    Console.WriteLine(input.FullSizeImageUrl);
                });

                imageManager.RequestImageForAsset(asset,
                                                  new CGSize(asset.PixelWidth, asset.PixelHeight),
                                                  PHImageContentMode.Default,
                                                  null,
                                                  (image, info) => {
                    imagePreview.Image = image;
                });
                await Task.Delay(1000);
            }
        }
        private async void SetGalleryButton()
        {
            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status == PHAuthorizationStatus.Authorized)
            {
                var fetchedAssets    = PHAsset.FetchAssets(PHAssetMediaType.Image, null);
                var lastGalleryPhoto = fetchedAssets.LastObject as PHAsset;
                if (lastGalleryPhoto != null)
                {
                    galleryButton.UserInteractionEnabled = true;
                    var PHImageManager = new PHImageManager();
                    PHImageManager.RequestImageForAsset(lastGalleryPhoto, new CGSize(300, 300),
                                                        PHImageContentMode.AspectFill, new PHImageRequestOptions()
                    {
                        DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic,
                        ResizeMode   = PHImageRequestOptionsResizeMode.Exact
                    }, (img, info) =>
                    {
                        galleryButton.Image = img;
                    });
                }
                else
                {
                    galleryButton.UserInteractionEnabled = false;
                }
            }
            else
            {
                galleryButton.UserInteractionEnabled = true;
            }
        }
 public ImageService()
 {
     this.imagesResult   = new List <NSObject>();
     this.imageManager   = PHImageManager.DefaultManager;
     this.requestOptions = new PHImageRequestOptions()
     {
         Synchronous = true
     };
 }
Ejemplo n.º 8
0
        public PhotoCollectionViewSource()
        {
            PHFetchOptions options = new PHFetchOptions
            {
                SortDescriptors = new[] { new NSSortDescriptor("creationDate", false) },
            };

            _fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
            _m            = new PHImageManager();
        }
Ejemplo n.º 9
0
        public PhotosViewController(UICollectionViewLayout layout) : base(layout)
        {
            Title = "All Photos";

            imageMgr     = new PHImageManager();
            fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, null);

            observer = new PhotoLibraryObserver(this);

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(observer);
        }
Ejemplo n.º 10
0
        public PhotosViewController(UICollectionViewLayout layout)
            : base(layout)
        {
            Title = "All Photos";

            imageMgr = new PHImageManager ();
            fetchResults = PHAsset.FetchAssets (PHAssetMediaType.Image, null);

            observer = new PhotoLibraryObserver (this);

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver (observer);
        }
Ejemplo n.º 11
0
        public void UpdateImage(PHImageManager cm, PHAsset photo, bool isCurrentlySelected, int count = 0, bool?isSelected = null)
        {
            if (_bodyImage == null)
            {
                CreateImageView();
            }

            if (_selectView == null)
            {
                _selectView = new UIView(new CGRect(ContentView.Frame.Right - 38, 8, 30, 30));
                _selectView.Layer.BorderColor  = UIColor.White.CGColor;
                _selectView.Layer.BorderWidth  = 2;
                _selectView.Layer.CornerRadius = 15;
                _selectView.BackgroundColor    = UIColor.Clear;
                _selectView.Hidden             = true;
                _selectView.ClipsToBounds      = true;
                ContentView.AddSubview(_selectView);
            }

            if (_countLabel == null)
            {
                _countLabel           = new UILabel();
                _countLabel.Font      = Constants.Semibold16;
                _countLabel.TextColor = UIColor.White;
                _selectView.AddSubview(_countLabel);
                _countLabel.AutoCenterInSuperview();
            }
            _countLabel.Text = (count + 1).ToString();


            if (_selectFrame == null)
            {
                _selectFrame = new UIView(ContentView.Frame);
                _selectFrame.Layer.BorderColor = Constants.R255G81B4.CGColor;
                _selectFrame.Layer.BorderWidth = 3;
                _selectFrame.BackgroundColor   = UIColor.Clear;

                ContentView.AddSubview(_selectFrame);
            }
            _selectFrame.Hidden = !isCurrentlySelected;

            ManageSelector(isSelected);

            cm.RequestImageForAsset(photo, new CGSize(200, 200),
                                    PHImageContentMode.AspectFill, new PHImageRequestOptions()
            {
                Synchronous = true
            }, (img, info) =>
            {
                _bodyImage.Image = img;
            });
        }
        public UILatestPhotosOverlayView(CGRect frame) : base(frame, new UIHorizontalScrollLayout())
        {
            DataSource = this;
            RegisterClassForCell(typeof(UIImageViewCell), imageViewCellId);
            fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, null);
            manager      = new PHImageManager();

            var tapRecognizer = new UITapGestureRecognizer(() => Console.Write("test"));

            AddGestureRecognizer(tapRecognizer);
            TranslatesAutoresizingMaskIntoConstraints = false;
            BackgroundColor = UIColor.Clear;
        }
        void GetPhotos()
        {
            if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.Authorized)
            {
                imageManager = PHImageManager.DefaultManager;

                PHFetchOptions options = new PHFetchOptions {
                    SortDescriptors = new [] { new NSSortDescriptor("creationDate", false) }
                };
                images = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
                CollectionView.ReloadData();
            }
        }
Ejemplo n.º 14
0
        private void FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
        {
            var originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
            var imageManager  = new PHImageManager();

            imageManager.RequestImageData(e.PHAsset, null, (data, dataUti, orientation, info) =>
            {
                var source   = CGImageSource.FromData(data);
                var metadata = source.GetProperties(0).Dictionary;

                GoToDescription(originalImage, UIDeviceOrientation.Portrait, metadata);
                _imagePicker.DismissViewControllerAsync(false);
            });
        }
Ejemplo n.º 15
0
        public async Task <IEnumerable <XMediaFile> > GetMediaFiles()
        {
            var images     = new List <XMediaFile>();
            var permission = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (permission == PHAuthorizationStatus.Authorized)
            {
                PHImageManager imageManager = PHImageManager.DefaultManager;

                var requestOptions = new PHImageRequestOptions()
                {
                    Synchronous = true
                };

                var results = PrepareResults();

                for (int i = 0; i < results.Count; i++)
                {
                    var asset = results.ObjectAt(i) as PHAsset;

                    imageManager.RequestImageForAsset(asset, new CGSize(100, 100), PHImageContentMode.AspectFill, requestOptions, (image, info) =>
                    {
                        var funcBytes = new Func <byte[]>(() =>
                        {
                            byte[] rawBytes = null;
                            using (NSData imageData = image.AsJPEG())
                            {
                                rawBytes = new Byte[imageData.Length];
                                System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, rawBytes, 0, (int)imageData.Length);
                            }

                            return(rawBytes);
                        });


                        images.Add(new XMediaFile()
                        {
                            Data      = funcBytes,
                            DateAdded = asset.CreationDate.ToDateTime().ToShortDate(),
                            MediaType = asset.MediaType.ToString()
                        });
                    });
                }

                return(images);
            }

            return(images);
        }
Ejemplo n.º 16
0
        public void UpdateCell(Tuple <string, PHFetchResult> album)
        {
            _currentAlbum = album;
            _name.Text    = _currentAlbum.Item1;
            _count.Text   = _currentAlbum.Item2.Count.ToString();
            var PHImageManager = new PHImageManager();

            PHImageManager.RequestImageForAsset((PHAsset)_currentAlbum.Item2.LastObject, new CGSize(300, 300),
                                                PHImageContentMode.AspectFill, new PHImageRequestOptions()
            {
                DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic,
                ResizeMode   = PHImageRequestOptionsResizeMode.Exact
            }, (img, info) =>
            {
                _lastImage.Image = img;
            });
        }
Ejemplo n.º 17
0
        private void ChangeImage(PHAsset asset, PHImageManager imageManager,
                                 PHImageRequestOptions options)
        {
            var assetSize = new CGSize(asset.PixelWidth, asset.PixelHeight);

            DispatchQueue.DefaultGlobalQueue.DispatchAsync(() =>
                                                           imageManager?.RequestImageForAsset(asset, assetSize,
                                                                                              PHImageContentMode.AspectFill, options,
                                                                                              (result, info) =>
                                                                                              DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                CurrentMediaType = MediaType.Image;
                _albumView.ImageCropView.Hidden    = false;
                _albumView.MovieView.Hidden        = true;
                _albumView.ImageCropView.ImageSize = assetSize;
                _albumView.ImageCropView.Image     = result;
            })));
        }
Ejemplo n.º 18
0
        private async Task <string> GetFileNamePHAsync(string path)
        {
            Debug.WriteLine("MediaFile: starting GetFileNamePHAsync");
            var nameTCS = new TaskCompletionSource <string>();

            using (var assetUrl = new NSUrl(path))
            {
                using (var asset = GetAssetPH(assetUrl))
                {
                    using (var manager = new PHImageManager())
                    {
                        Debug.WriteLine("MediaFile: requesting image data for {0}", (object)path);

                        manager.RequestImageData(asset,
                                                 new PHImageRequestOptions {
                            Synchronous = true
                        },
                                                 (data, dataUti, orientation, info) =>
                        {
                            Debug.WriteLine("MediaFile: image data request returned");
                            var imageName = "Unknown";
                            var fileUrl   = info["PHImageFileURLKey"].ToString();
                            if (!string.IsNullOrWhiteSpace(fileUrl))
                            {
                                var slash = fileUrl.LastIndexOf('/');
                                if (slash > -1)
                                {
                                    imageName = fileUrl.Substring(slash + 1);
                                }
                            }
                            Debug.WriteLine("MediaFile: image name set to {0}", (object)imageName);
                            nameTCS.SetResult(imageName);
                        });
                        Debug.WriteLine("MediaFile: awaiting image name");
                        await nameTCS.Task;
                    }
                }
            }
            var name = nameTCS.Task.Result;

            Debug.WriteLine("MediaFile: image name returned {0}", (object)name);
            return(name);
        }
Ejemplo n.º 19
0
        private void ChangeVideo(PHAsset asset, PHImageManager imageManager,
                                 PHVideoRequestOptions options)
        {
            DispatchQueue.DefaultGlobalQueue.DispatchAsync(() =>
                                                           imageManager?.RequestAvAsset(asset, options,
                                                                                        (ass, mix, info) =>
                                                                                        DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                CurrentMediaType = MediaType.Video;
                _albumView.ImageCropView.Hidden = true;
                _albumView.MovieView.Hidden     = false;

                var urlAsset = ass as AVUrlAsset;
                if (urlAsset == null)
                {
                    return;
                }
                _albumView.MoviePlayerController.ContentUrl = urlAsset.Url;
                _albumView.MoviePlayerController.PrepareToPlay();
            })));
        }
Ejemplo n.º 20
0
        private async void SetGalleryButton()
        {
            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status == PHAuthorizationStatus.Authorized)
            {
                var options = new PHFetchOptions
                {
                    SortDescriptors = new[] { new NSSortDescriptor("creationDate", false) },
                    FetchLimit      = 5,
                };

                var fetchedAssets    = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
                var lastGalleryPhoto = fetchedAssets.FirstOrDefault() as PHAsset;
                if (lastGalleryPhoto != null)
                {
                    galleryButton.UserInteractionEnabled = true;
                    var PHImageManager = new PHImageManager();
                    PHImageManager.RequestImageForAsset(lastGalleryPhoto, new CGSize(300, 300),
                                                        PHImageContentMode.AspectFill, new PHImageRequestOptions()
                    {
                        DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic,
                        ResizeMode   = PHImageRequestOptionsResizeMode.Exact
                    }, (img, info) =>
                    {
                        galleryButton.Image = img;
                    });
                }
                else
                {
                    galleryButton.UserInteractionEnabled = false;
                }
            }
            else
            {
                galleryButton.UserInteractionEnabled = true;
            }
        }
Ejemplo n.º 21
0
        void exration()
        {   //change
            saveFormGrally.Clear();

            // Imagedata.Clear();
            int            icount       = _multiAsset.Assets.Count();
            string         date         = string.Empty;
            UIImageView    imag         = new UIImageView();
            iEbutton       button       = new iEbutton();
            string         endex        = string.Empty;
            PHImageManager imageManager = new PHImageManager();
            // bool isvideo = false;
            UIImage image1 = new UIImage();

            //  byetdata = new List<byte[]>();
            foreach (PHAsset asset in _multiAsset.Assets)
            {
                save_Plus save    = new save_Plus();
                bool      isvideo = false;

                AVPlayer avplayer = new AVPlayer();

                if (asset.MediaType == PHAssetMediaType.Video)
                {
                    isvideo = true;
                    // NSUrl videoUrl = null;

                    imageManager.RequestAvAsset(asset, null, (avsset, avaudio, NsD) =>
                    {
                        //   string UrlConvertString = null;

                        var videoUrl            = ((AVFoundation.AVUrlAsset)avsset).Url;
                        string UrlConvertString = (videoUrl.AbsoluteString);
                        save.Url       = UrlConvertString;
                        save.Extension = "Video";
                        // UrlVideoString.Add(UrlConvertString);
                    });
                }

                imageManager.RequestImageForAsset(asset,
                                                  new CGSize(asset.PixelWidth, asset.PixelHeight),
                                                  PHImageContentMode.Default,
                                                  null,
                                                  (image, info) =>
                {
                    //  endex = image.AccessibilityPath.ToString();

                    //  endex = "jpg";

                    //

                    if (!isvideo)
                    {
                        save.Image     = image;
                        save.Thumbnail = image;
                        save.Extension = "Image";
                        // byte[] myByteArray;
                        // using (NSData imageData = image.AsPNG())
                        // {
                        //     myByteArray = new Byte[imageData.Length];
                        //     System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length));


                        // }


                        // string random = GeneratePassword(7);



                        //// Imagedata.Add(image);
                        //   DataSql.process(library.File(2), library.INSERT(2), DataSql_Parameters(random + ".jpg", myByteArray, "image"));
                        //node
                    } // if isvideo
                    else
                    {
                        save.Thumbnail = image;
                    }
                    isvideo = true;

                    // button.creation(i, image);

                    //  date = DateTime.Now.ToString("MMddHHmmss");
                    icount--;
                    saveFormGrally.Add(save);
                    Thread.Sleep(500);
                });
            }
            //button.getText(date);
            //button.click += Button_TouchUpInside; ;
            // isvideo = false;

            //UIbutton.Add(button);
            //  lab.Text = ImageView.Count.ToString();

            // Imagedata.Add(image1);



            //nd foreach}
            _multiAsset = null;
            todatabese();
            finshpluse = 1;
        }
 public PhotoCollectionViewSource(PHImageManager m)
 {
     _m = m;
 }
Ejemplo n.º 23
0
 private async Task<Stream> GetStreamPHAsync(string path)
 {
     Debug.WriteLine("MediaFile: GetStreamPH entered with path = {0}", (object)path);
     var streamCompletion = new TaskCompletionSource<Stream>();
     using (var assetUrl = new NSUrl(path))
     {
         using (var asset = GetAssetPH(assetUrl))
         {
             var imageDataTCS = new TaskCompletionSource<NSData>();
             NSData imgData;
             using (var manager = new PHImageManager())
             {
                 manager.RequestImageData(
                     asset,
                     null,
                     (data, dataUti, orientation, info) =>
                     {
                         Debug.WriteLine("MediaFile: data is {0} bytes", data.Length);
                         imageDataTCS.SetResult(data);
                     });
                 Debug.WriteLine("MediaFile: waiting for imgData");
                 imgData = await imageDataTCS.Task.ConfigureAwait(false);
             }
             Debug.WriteLine("MediaFile: imgData is {0} bytes", imgData.Length);
             streamCompletion.SetResult(imgData.AsStream());
         }
     }
     Debug.WriteLine("MediaFile: waiting for stream");
     var stream = await streamCompletion.Task;
     Debug.WriteLine("MediaFile: stream returned with length {0}", stream.Length);
     return stream;
 }
Ejemplo n.º 24
0
        private async Task<string> GetFileNamePHAsync(string path)
        {
            Debug.WriteLine("MediaFile: starting GetFileNamePHAsync");
            var nameTCS = new TaskCompletionSource<string>();
            using (var assetUrl = new NSUrl(path))
            {
                using (var asset = GetAssetPH(assetUrl))
                {
                    using (var manager = new PHImageManager())
                    {
                        Debug.WriteLine("MediaFile: requesting image data for {0}", (object)path);

                        manager.RequestImageData(asset,
                            new PHImageRequestOptions { Synchronous = true },
                            (data, dataUti, orientation, info) =>
                            {
                                Debug.WriteLine("MediaFile: image data request returned");
                                var imageName = "Unknown";
                                var fileUrl = info["PHImageFileURLKey"].ToString();
                                if (!string.IsNullOrWhiteSpace(fileUrl))
                                {
                                    var slash = fileUrl.LastIndexOf('/');
                                    if (slash > -1)
                                        imageName = fileUrl.Substring(slash + 1);
                                }
                                Debug.WriteLine("MediaFile: image name set to {0}", (object)imageName);
                                nameTCS.SetResult(imageName);
                            });
                        Debug.WriteLine("MediaFile: awaiting image name");
                        await nameTCS.Task;
                    }
                }
            }
            var name = nameTCS.Task.Result;
            Debug.WriteLine("MediaFile: image name returned {0}", (object)name);
            return name;
        }
 public PhotosViewController(IntPtr handle) : base(handle)
 {
     imageManager = new PHImageManager();
     Images       = PHAsset.FetchAssets(PHAssetMediaType.Image, null);
     PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(observer = new PhotoLibraryObserver(this));
 }
Ejemplo n.º 26
0
        public void ShowImagePicker(bool needsHighQuality)
        {
            //Create the image gallery picker.
            var picker = new GMImagePickerController
            {
                Title = "Select Photo",
                CustomDoneButtonTitle       = "Finished",
                CustomCancelButtonTitle     = "Cancel",
                ColsInPortrait              = 4,
                ColsInLandscape             = 7,
                MinimumInteritemSpacing     = 2.0f,
                DisplaySelectionInfoToolbar = true,
                AllowsMultipleSelection     = true,
                ShowCameraButton            = true,
                AutoSelectCameraImages      = true,
                ModalPresentationStyle      = UIModalPresentationStyle.Popover,
                MediaTypes             = new[] { PHAssetMediaType.Image },
                CustomSmartCollections = new[]
                {
                    PHAssetCollectionSubtype.SmartAlbumUserLibrary,
                    PHAssetCollectionSubtype.AlbumRegular
                },
                NavigationBarTextColor    = Color.White.ToUIColor(),
                NavigationBarBarTintColor = Color.FromHex("#c5dd36").ToUIColor(),
                PickerTextColor           = Color.Black.ToUIColor(),
                ToolbarTextColor          = Color.FromHex("#c5dd36").ToUIColor(),
                NavigationBarTintColor    = Color.White.ToUIColor()
            };

            //Set a limit on the number of photos the user can select. I use 12 selected photos beause of memory limitations on iOS.
            picker.ShouldSelectAsset += (sender, args) => args.Cancel = picker.SelectedAssets.Count > 11;

            // select image handler
            GMImagePickerController.MultiAssetEventHandler[] handler = { null };
            //cancel handler
            EventHandler[] cancelHandler = { null };

            //define the handler
            handler[0] = (sender, args) =>
            {
                var tcs = Interlocked.Exchange(ref _completionSource, null);
                picker.FinishedPickingAssets -= handler[0];
                picker.Canceled -= cancelHandler[0];
                System.Diagnostics.Debug.WriteLine("User finished picking assets. {0} items selected.", args.Assets.Length);
                var imageManager       = new PHImageManager();
                var RequestImageOption = new PHImageRequestOptions();

                if (needsHighQuality)
                {
                    RequestImageOption.DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat;
                }
                else
                {
                    RequestImageOption.DeliveryMode = PHImageRequestOptionsDeliveryMode.FastFormat;
                }

                RequestImageOption.ResizeMode           = PHImageRequestOptionsResizeMode.Fast;
                RequestImageOption.NetworkAccessAllowed = true;
                RequestImageOption.Synchronous          = false;
                _preselectedAssets = args.Assets;
                if (!_preselectedAssets.Any())
                {
                    //no image selected
                    tcs.TrySetResult(null);
                }
                else
                {
                    var images             = new List <string>();
                    var documentsDirectory = Environment.GetFolderPath
                                                 (Environment.SpecialFolder.Personal);
                    int cnt = 1;
                    foreach (var asset in _preselectedAssets)
                    {
                        DispatchQueue.MainQueue.DispatchAsync(() =>
                        {
                            //For each image, create a file path for it.
                            imageManager.RequestImageForAsset(asset,
                                                              PHImageManager.MaximumSize,
                                                              PHImageContentMode.Default,
                                                              RequestImageOption,
                                                              (image, info) =>
                            {
                                using (NSAutoreleasePool autoreleasePool = new NSAutoreleasePool())
                                {
                                    System.Diagnostics.Debug.WriteLine("Total memory being used: {0}", GC.GetTotalMemory(false));
                                    var filename = Guid.NewGuid().ToString();
                                    System.Diagnostics.Debug.WriteLine("filename: " + filename);
                                    string filepath = Save(image, filename.ToString(), documentsDirectory);
                                    System.Diagnostics.Debug.WriteLine("filepath: " + filepath);
                                    images.Add(filepath);

                                    //When we are on the last image, send the images to the carousel view.
                                    if (cnt == args.Assets.Length)
                                    {
                                        Device.BeginInvokeOnMainThread(() =>
                                        {
                                            MessagingCenter.Send <App, List <string> >((App)Xamarin.Forms.Application.Current, "ImagesSelectediOS", images);
                                        });
                                    }
                                    cnt++;

                                    //Dispose of objects and call the garbage collector.
                                    asset.Dispose();
                                    autoreleasePool.Dispose();
                                    GC.Collect();
                                }
                            });
                        });
                    }
                    tcs.TrySetResult(images);
                }
            };
            picker.FinishedPickingAssets += handler[0];

            cancelHandler[0] = (sender, args) =>
            {
                var tcs = Interlocked.Exchange(ref _completionSource, null);
                picker.FinishedPickingAssets -= handler[0];
                picker.Canceled -= cancelHandler[0];
                tcs.TrySetResult(null);
            };
            picker.Canceled += cancelHandler[0];

            //show picker
            picker.PresentUsingRootViewController();
        }
Ejemplo n.º 27
0
      //puls button;
      private void Picker_FinishedPickingAssets(object sender, MultiAssetEventArgs args)
      {
          UrlVideoString.Clear();
          Imagedata.Clear();
          // Imagedata = null;
          bool    isvideo = false;
          int     i       = buttonnumber;
          PHAsset pHAsset = args.Assets[0];

          // imgView.Image= pHAsset.Location

          //    uIImage. = pHAsset.Location();
          //   List<  UIImage> uIImage = new List<UIImage> ();
          PHImageManager imageManager = new PHImageManager();

          foreach (var asset in args.Assets)
          {  //
              string      date   = string.Empty;
              UIImageView imag   = new UIImageView();
              iEbutton    button = new iEbutton();
              string      endex  = string.Empty;


              UIImage  image1   = new UIImage();
              AVPlayer avplayer = new AVPlayer();
              if (asset.MediaType == PHAssetMediaType.Video)
              {
                  isvideo = true;
                  // NSUrl videoUrl = null;

                  imageManager.RequestAvAsset(asset, null, (avsset, avaudio, NsD) =>
                    {
                        //   string UrlConvertString = null;

                        var videoUrl            = ((AVFoundation.AVUrlAsset)avsset).Url;
                        string UrlConvertString = (videoUrl.AbsoluteString);

                        UrlVideoString.Add(UrlConvertString);
                    });
              }

              imageManager.RequestImageForAsset(asset,
                                                new CGSize(asset.PixelWidth, asset.PixelHeight),
                                                PHImageContentMode.Default,
                                                null,
                                                (image, info) =>
                {
                    //  endex = image.AccessibilityPath.ToString();

                    //  endex = "jpg";

                    //

                    if (isvideo == false)
                    {
                        image1 = image;

                        imag.Image = image;
                        Imagedata.Add(image1);
                        // button.creation(i, image);
                    }

                    //  date = DateTime.Now.ToString("MMddHHmmss");

                    Thread.Sleep(1000);
                });

              //button.getText(date);
              //button.click += Button_TouchUpInside; ;
              isvideo = false;

              //UIbutton.Add(button);
              //  lab.Text = ImageView.Count.ToString();

              // Imagedata.Add(image1);
          }  //end foreach

          // finshpluse = 1;

          //  imgView.Image = uIImage[uIImage.Count-1];



          //  scoll = new UIScrollView();
          //if (scoll.Frame.Height > scoll.Frame.Width )
          //{

          //    scoll.ContentSize = new CGSize(uiv.Frame.Width -70, ImageView.Count * 15);
          //    putimage(50,70,14);

          //}

          //else { scoll.ContentSize = new CGSize(ImageView.Count+20, ImageView.Count * 15);


          //    putimage(80, 90, 40);



          //}
          finshpluse = 1;
          todatabese();
      }
        public void ShowImagePicker()
        {
            var picker = new GMImagePickerController
            {
                Title = "Select Media",
                CustomDoneButtonTitle       = "Finished",
                CustomCancelButtonTitle     = "Cancel",
                ColsInPortrait              = 3,
                ColsInLandscape             = 5,
                MinimumInteritemSpacing     = 2.0f,
                DisplaySelectionInfoToolbar = true,
                AllowsMultipleSelection     = true,
                ShowCameraButton            = true,
                AutoSelectCameraImages      = true,
                ModalPresentationStyle      = UIModalPresentationStyle.Popover,
                MediaTypes             = new[] { PHAssetMediaType.Image },
                CustomSmartCollections = new[]
                {
                    PHAssetCollectionSubtype.SmartAlbumUserLibrary,
                    PHAssetCollectionSubtype.AlbumRegular
                },
                NavigationBarTextColor    = Color.White.ToUIColor(),
                NavigationBarBarTintColor = Color.FromRgb(10, 82, 134).ToUIColor(),
                PickerTextColor           = Color.White.ToUIColor(),
                ToolbarTextColor          = Color.FromRgb(10, 82, 134).ToUIColor(),
                NavigationBarTintColor    = Color.White.ToUIColor()
            };

            // You can limit which galleries are available to browse through
            if (_preselectedAssets != null)
            {
                foreach (var asset in _preselectedAssets)
                {
                    picker.SelectedAssets.Add(asset);
                }
            }

            // select image handler
            GMImagePickerController.MultiAssetEventHandler[] handler = { null };
            //cancel handler
            EventHandler[] cancelHandler = { null };

            //define
            handler[0] = (sender, args) =>
            {
                System.Diagnostics.Debug.WriteLine("User canceled picking image.");
                var tcs = Interlocked.Exchange(ref _completionSource, null);
                picker.FinishedPickingAssets -= handler[0];
                picker.Canceled -= cancelHandler[0];
                System.Diagnostics.Debug.WriteLine("User finished picking assets. {0} items selected.", args.Assets.Length);
                var imageManager = new PHImageManager();
                _preselectedAssets = args.Assets;
                if (!_preselectedAssets.Any())
                {
                    //no image selected
                    tcs.TrySetResult(null);
                }
                else
                {
                    var imageSources = new List <ImageSource>();
                    foreach (var asset in _preselectedAssets)
                    {
                        imageManager.RequestImageForAsset(asset,
                                                          new CGSize(asset.PixelWidth, asset.PixelHeight),
                                                          PHImageContentMode.Default,
                                                          null,
                                                          (image, info) => {
                            imageSources.Add(image.GetImageSourceFromUIImage());
                        });
                    }

                    tcs.TrySetResult(imageSources);
                }
            };
            picker.FinishedPickingAssets += handler[0];

            cancelHandler[0] = (sender, args) =>
            {
                var tcs = Interlocked.Exchange(ref _completionSource, null);
                picker.FinishedPickingAssets -= handler[0];
                picker.Canceled -= cancelHandler[0];
                tcs.TrySetResult(null);
            };
            picker.Canceled += cancelHandler[0];

            //show picker
            picker.PresentUsingRootViewController();
        }
Ejemplo n.º 29
0
 public PhotoPreviewViewController()
 {
     _m = new PHImageManager();
 }
		async void Picker_FinishedPickingAssets (object sender, MultiAssetEventArgs args)
		{
			PHImageManager imageManager = new PHImageManager();

			Console.WriteLine ("User finished picking assets. {0} items selected.", args.Assets.Length);

			_preselectedAssets = args.Assets;

			// For demo purposes: just show all chosen pictures in order every second
			foreach (var asset in args.Assets) {
				imagePreview.Image = null;

				imageManager.RequestImageForAsset (asset, 
					new CGSize(asset.PixelWidth, asset.PixelHeight), 
					PHImageContentMode.Default, 
					null, 
					(image, info) => {
						imagePreview.Image = image;
				});
				await Task.Delay (1000);
			}
		}