Ejemplo n.º 1
0
        /// <summary>
        /// Gets the picture media file.
        /// </summary>
        /// <param name="info">The information.</param>
        /// <returns>MediaFile.</returns>
        private void GetPictureMediaFile(NSDictionary info, Action <MediaFile> callback)
        {
            var image = (UIImage)info[UIImagePickerController.OriginalImage];

            var referenceURL = (NSUrl)info[UIImagePickerController.ReferenceUrl];

            if (referenceURL == null) //from camera
            {
                var             metadata = (NSDictionary)info[UIImagePickerController.MediaMetadata];
                ALAssetsLibrary library  = new ALAssetsLibrary();
                library.WriteImageToSavedPhotosAlbum(image.CGImage, metadata, (assetUrl, error) => {
                });
                GetPictureMediaFileWithMetadata(metadata, image, callback);
            }
            else // from albun
            {
                ALAssetsLibrary library = new ALAssetsLibrary();
                library.AssetForUrl(referenceURL, (ALAsset asset) =>
                {
                    ALAssetRepresentation rep = asset.DefaultRepresentation;
                    NSDictionary metadata     = rep.Metadata;
                    var cgimg = rep.GetFullScreenImage();
                    var img   = new UIImage(cgimg);
                    GetPictureMediaFileWithMetadata(metadata, img, callback);
                }, (e) =>
                {
                });
            }
        }
Ejemplo n.º 2
0
        protected void Handle_FinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
        {
            bool isImage = false;

            switch (e.Info[UIImagePickerController.MediaType].ToString())
            {
            case "public.image":
                isImage = true;
                break;

            case "public.video":
                break;
            }

            // get common info (shared between images and video)
            NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceURL")] as NSUrl;

            fileName = null;

            ALAssetsLibrary assetsLibrary = new ALAssetsLibrary();

            assetsLibrary.AssetForUrl(referenceURL, delegate(ALAsset asset)
            {
                ALAssetRepresentation representation = asset.DefaultRepresentation;
                if (representation == null)
                {
                    return;
                }
                else
                {
                    fileName = representation.Filename.ToLower();
                }
            }, delegate(NSError error) {});

            if (isImage)
            {
                UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
                if (originalImage != null)
                {
                    profileImageView.Image = originalImage;
                    fileName = "1.jpg";
                    Update(true);
                }
            }
            else
            {
                NSUrl mediaURL = e.Info[UIImagePickerController.MediaURL] as NSUrl;
                if (mediaURL != null)
                {
                    Console.WriteLine(mediaURL.ToString());
                }
            }
            imagePicker.DismissModalViewController(true);
        }
Ejemplo n.º 3
0
        public static void setCurrentPhotoToIndex(int index)
        {
            currentAsset = photoAssets [index];
            ALAssetRepresentation rep = currentAsset.RepresentationForUti("public.jpeg");
            CGImage imageRef          = rep.GetFullScreenImage();

            if (imageRef != null)
            {
                currentPhotoImage = UIImage.FromImage(imageRef);
                currentPhotoIndex = index;
            }
        }
        private void BuildFileAttachment(UIImagePickerMediaPickedEventArgs media)
        {
            string name = "";

            // Build attachment and show in view

            NSUrl referenceURL = media.Info[new NSString("UIImagePickerControllerReferenceURL")] as NSUrl;

            if (referenceURL != null)
            {
                ALAssetsLibrary assetsLibrary = new ALAssetsLibrary();
                assetsLibrary.AssetForUrl(referenceURL, delegate(ALAsset asset) {
                    ALAssetRepresentation representation = asset.DefaultRepresentation;

                    if (representation != null)
                    {
                        name = representation.Filename;
                    }

                    string nameFile = name.Length > 0 ? name : "Archivo Adjunto " + (AttachmentFilesInMemory.Count + 1).ToString();

                    AttachmentFile attachmentFile = new AttachmentFile();
                    attachmentFile.FileName       = nameFile;
                    attachmentFile.Private        = privateFile;

                    // Get image and convert to BytesArray
                    UIImage originalImage = media.Info[UIImagePickerController.OriginalImage] as UIImage;

                    if (originalImage != null)
                    {
                        string extension = referenceURL.PathExtension;

                        using (NSData imageData = originalImage.AsJPEG(0.5f))
                        {
                            Byte[] fileByteArray = new Byte[imageData.Length];
                            Marshal.Copy(imageData.Bytes, fileByteArray, 0, Convert.ToInt32(imageData.Length));
                            attachmentFile.BytesArray = fileByteArray;
                        }
                    }


                    AttachmentFilesInMemory.Add(attachmentFile);

                    // Show file selected in view
                    LoadAttachmentsOfEvent();
                }, delegate(NSError error) {
                    return;
                });
            }
        }
        /// <summary>
        /// Asynchronous processing of the image selection event.
        /// The below is standard iOS code (via Xamarin classes) needed to extract the file name and the content of the selected image file
        /// </summary>
        async void ImagePicker_FinishedPickingMediaAsync(UIImagePickerMediaPickedEventArgs e)
        {
            try
            {
                string mediaTypeName = e.Info [UIImagePickerController.MediaType].ToString();
                if (string.Compare(mediaTypeName, "public.image", true) != 0)
                {
                    Console.WriteLine("No image was selected.");
                    CloseAndDisposeImagePicker();
                    return;
                }

                using (NSUrl nsUrl = e.Info[UIImagePickerController.ReferenceUrl] as NSUrl)
                {
                    if (nsUrl == null)
                    {
                        Console.WriteLine("Could not get URL for the selected image.");
                        CloseAndDisposeImagePicker();
                        return;
                    }

                    using (var assetsLib = new ALAssetsLibrary())
                    {
                        assetsLib.AssetForUrl(
                            nsUrl,
                            (ALAsset asset) =>
                        {
                            using (ALAssetRepresentation assetRep = asset.DefaultRepresentation)
                            {
                                UIImage originalImage;
                                using (var assetStream = new AssetLibraryReadStream(assetRep)) originalImage = UIImage.LoadFromData(NSData.FromStream(assetStream));
                                this.ExpenseImageData      = originalImage.AsJPEG(0.1f).ToArray();
                                ReceiptImageTextField.Text = assetRep.Filename;
                                CloseAndDisposeImagePicker();
                            }
                        },
                            (NSError error) => { throw new IOException("Error when getting asset for URL."); }
                            );
                    }
                }
            }
            catch (Exception ex)
            {
                CloseAndDisposeImagePicker();
                DisplayException(ex);
            }
        }
Ejemplo n.º 6
0
        public static void setCurrentPhotoToIndex(int index)
        {
            currentAsset = photoAssets [index];
            ALAssetRepresentation rep = currentAsset.RepresentationForUti("public.jpeg");

            // image might not be available as a JPEG
            if (rep == null)
            {
                return;
            }
            CGImage imageRef = rep.GetFullScreenImage();

            if (imageRef == null)
            {
                return;
            }
            currentPhotoImage = UIImage.FromImage(imageRef);
            currentPhotoIndex = index;
        }
 /// <summary>
 /// A readonly stream to access an Asset resource
 /// see http://msdn.microsoft.com/en-us/library/system.io.stream.aspx
 /// </summary>
 public AssetLibraryReadStream(ALAssetRepresentation assetRep)
 {
     this.AssetRep = assetRep;
     this.Position = 0;
 }
Ejemplo n.º 8
0
        public bool SavePhotoAsync(byte[] data, string directory, string folder, string filename, ref string fullpath)
        {
            try
            {
                ////code1
                //NSData nsData = NSData.FromArray(data);
                //UIImage image = new UIImage(nsData);
                //TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();

                //image.SaveToPhotosAlbum((UIImage img, NSError error) =>
                //{
                //    taskCompletionSource.SetResult(error == null);
                //});

                //return taskCompletionSource.Task;


                //Code2
                var AbsolutePath = string.Empty;
                // First, check to see if we have initially asked the user for permission
                // to access their photo album.
                if (Photos.PHPhotoLibrary.AuthorizationStatus ==
                    Photos.PHAuthorizationStatus.NotDetermined)
                {
                    var status =
                        Plugin.Permissions.CrossPermissions.Current.RequestPermissionsAsync(
                            Plugin.Permissions.Abstractions.Permission.Photos);
                }
                if (Photos.PHPhotoLibrary.AuthorizationStatus ==
                    Photos.PHAuthorizationStatus.Authorized)
                {
                    NSData  nsData = NSData.FromArray(data);
                    UIImage image  = new UIImage(nsData);
                    TaskCompletionSource <bool> taskCompletionSource = new TaskCompletionSource <bool>();
                    var dict = new NSDictionary();
                    // This bit of code saves to the Photo Album with metadata
                    ALAssetsLibrary library = new ALAssetsLibrary();
                    library.WriteImageToSavedPhotosAlbum(image.CGImage, dict, (assetUrl, error) =>
                    {
                        AbsolutePath = assetUrl.ToString();
                        library.AssetForUrl(assetUrl, delegate(ALAsset asset)
                        {
                            AbsolutePath = assetUrl.LastPathComponent;
                            ALAssetRepresentation representation = asset.DefaultRepresentation;
                            if (representation != null)
                            {
                                string fileName  = representation.Filename != null ? representation.Filename : string.Empty;
                                var filePath     = assetUrl.ToString();
                                var extension    = filePath.Split('.')[1].ToLower();
                                var mimeData     = string.Format("image/{0}", extension);
                                var mimeType     = mimeData.Split('?')[0].ToLower();
                                var documentName = assetUrl.Path.ToString().Split('/')[1];
                                taskCompletionSource.SetResult(error == null);
                            }
                        }, delegate(NSError err)
                        {
                            Console.WriteLine("User denied access to photo Library... {0}", err);
                        });
                    });
                    fullpath = AbsolutePath;
                    return(true);
                }
                else
                {
                    return(false);
                }


                //Code3
                //bool success = false;

                //NSData imgData = NSData.FromArray(data);
                //UIKit.UIImage photo = new UIImage(imgData);

                //var savedImageFilename = System.IO.Path.Combine(directory, "temp");
                //savedImageFilename = System.IO.Path.Combine(savedImageFilename, filename);
                //NSFileManager.DefaultManager.CreateDirectory(savedImageFilename, true, null);

                //if (System.IO.Path.GetExtension(filename).ToLower() == ".png")
                //    imgData = photo.AsPNG();
                //else
                //    imgData = photo.AsJPEG(100);

                ////File.WriteAllBytes(savedImageFilename, data);

                //NSError err = null;
                //success = imgData.Save(savedImageFilename, NSDataWritingOptions.Atomic, out err);

                //return Task.FromResult(success);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }