Exemplo n.º 1
0
        public async Task GetThumbnailSource(ItemModel item)
        {
            await Task.Run(() =>
            {
                var requestId = _imageMgr.RequestImageForAsset(
                    _asset,
                    new CoreGraphics.CGSize(256, 256),
                    PHImageContentMode.AspectFill, new PHImageRequestOptions(),
                    async(img, info) =>
                {
                    if (img?.Size != null)         // && (img.Size.Width >= 256 || img.Size.Height >= 256))
                    {
                        await Task.Run(() =>
                        {
                            var imgSource    = ImageSource.FromStream(img.AsPNG().AsStream);
                            item.ThumbSource = imgSource;
                        }).ConfigureAwait(false);
                    }
                }
                    );

                Console.WriteLine($"ID: {requestId}");

                _requestsQueue.Enqueue(requestId);

                if (_requestsQueue.Count > 40)
                {
                    var oldRequestId = (int)_requestsQueue.Dequeue();

                    var t = Task.Run(() => { _imageMgr.CancelImageRequest(oldRequestId); });
                }
            }).ConfigureAwait(false);
        }
        // TODO MAKE ASYNC
        public List <ImageMediaContent> loadImages()
        {
            List <ImageMediaContent> imageMedia = new List <ImageMediaContent>();

            PHFetchResult fetchResult = PHAsset.FetchAssets(PHAssetMediaType.Image, null);

            nint index = 0;

            foreach (PHAsset phAsset in fetchResult)
            {
                String filePath = "";

                UIImage image;

                imageManager.RequestImageForAsset((PHAsset)imageFetchResults[index], new SizeF(160, 160),
                                                  PHImageContentMode.AspectFill, new PHImageRequestOptions(), (img, info) =>
                {
                    image = img;
                });

                index++;

                phAsset.RequestContentEditingInput(new PHContentEditingInputRequestOptions(), (input, v) =>
                {
                    filePath = input.FullSizeImageUrl.Path;
                });

                imageMedia.Add(new ImageMediaContent(filePath));
            }

            return(imageMedia);
        }
        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;
            }
        }
        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");
                }
            }
        }
Exemplo 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);
            }
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
        public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
        {
            var imageCell = (PhotoCollectionViewCell)collectionView.DequeueReusableCell(nameof(PhotoCollectionViewCell), indexPath);

            _m.RequestImageForAsset((PHAsset)_fetchResults[indexPath.Item], new CoreGraphics.CGSize(150, 150),
                                    PHImageContentMode.AspectFit, new PHImageRequestOptions(), (img, info) =>
            {
                imageCell.UpdateImage(img, (PHAsset)_fetchResults[indexPath.Item]);
            });
            return(imageCell);
        }
        public UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
        {
            UIImageViewCell cell = (UIImageViewCell)collectionView.DequeueReusableCell(imageViewCellId, indexPath);

            manager.RequestImageForAsset((PHAsset)fetchResults[indexPath.Item], new CGSize(240f, 240f),
                                         PHImageContentMode.AspectFill, new PHImageRequestOptions(), (img, info) => {
                cell.ImageView.Image = img;
            });

            return(cell);
        }
        public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
        {
            var imageCell = (ImageCell)collectionView.DequeueReusableCell(cellId, indexPath);

            imageMgr.RequestImageForAsset((PHAsset)fetchResults[indexPath.Item], new SizeF(160, 160),
                                          PHImageContentMode.AspectFill, new PHImageRequestOptions(), (img, info) => {
                imageCell.ImageView.Image = img;
            });

            return(imageCell);
        }
Exemplo n.º 10
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 override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
        {
            if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.Authorized)
            {
                var asset = images [indexPath.Item] as PHAsset;

                var cell = collectionView.DequeueReusableCell(PhotoCell.Key, indexPath) as PhotoCell;
                cell.AssetId = asset.LocalIdentifier;

                imageManager.RequestImageForAsset(asset, thumbnailSize, PHImageContentMode.AspectFill, null, (result, info) => {
                    // The cell may have been recycled by the time this handler gets called;
                    // set the cell's thumbnail image only if it's still showing the same asset.
                    if (cell.AssetId == asset.LocalIdentifier)
                    {
                        cell.Image = result;
                    }
                });

                return(cell);
            }

            return(collectionView.DequeueReusableCell("PermissionCell", indexPath) as UICollectionViewCell);
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
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;
            });
        }
Exemplo n.º 14
0
        private void CellAction(ActionType type, Tuple <NSIndexPath, PHAsset> photo)
        {
            if (type == ActionType.Close)
            {
                ShowAlert(Core.Localization.LocalizationKeys.PickedPhotosLimit);
                return;
            }
            NavigationItem.RightBarButtonItem.Enabled = false;
            pickedPhoto = photo;
            previousPhotoLocalIdentifier = source.CurrentlySelectedItem?.Item2?.LocalIdentifier;
            var pickOptions = new PHImageRequestOptions()
            {
                ResizeMode = PHImageRequestOptionsResizeMode.Exact, DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat
            };
            var imageSize = ImageHelper.CalculateInSampleSize(new CGSize(photo.Item2.PixelWidth, photo.Item2.PixelHeight), Core.Constants.PhotoMaxSize, Core.Constants.PhotoMaxSize);

            _m.RequestImageForAsset(photo.Item2, imageSize, PHImageContentMode.Default, pickOptions, PickImage);
        }
Exemplo n.º 15
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;
            })));
        }
Exemplo n.º 16
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;
            }
        }
		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);
			}
		}
Exemplo n.º 18
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();
        }
Exemplo n.º 20
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();
        }
Exemplo 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;
        }