How to select multiple images from gallery from both android and iOS device?

Hello,
I am working on xamarin.forms app. I am creating the app for android and iOS. I need to open the gallery and select multiple images from gallery of devices. How I can do this in xamarin.forms that can work for both android and iOS?

Regards,
Anand Dubey

Answers

  • Hello Anand,

    did you find any solution on this problem? I'm facing the same issue...

    Thank you,
    Simone

  • Hi Simone,

    Sorry still I don't have any solution. I am using CrossMedia (Xamarin.Plugin) for selecting image from gallery. But it selects only one image at a time. I am trying to make some changes in its library code so that it can select multiple image. But still not getting any success in it.

    Please update me if you get any success to select multiple images. I am also trying my best to find any best solution for it.

    Regards,
    Anand Dubey

  • alekssmykalekssmyk USMember ✭✭✭

    @AnandDubey.4112 @SimoneAgostini for android platform i use such type of code:
    Intent intent = new Intent(Intent.ActionView, Android.Provider.MediaStore.Images.Media.ExternalContentUri);
    this.StartActivityForResult(Intent.CreateChooser(intent, "Select a Photo"), 0);

    It shows intent and you can select multiply images, then click import with application and your selected images will be as params in the mainactivity.

  • Hi Dean,

    Thanks for your reply but I need a code that can work for both iOS and android. Do you have any idea how to do this in iOS. I am working on xamarin.forms. So I need a code that can work for both.

  • PatriciaRyanPatriciaRyan CAMember

    Charlin: this works except how do I get the selected photos once user has finished selecting them?

  • CharlinCharlin DOUniversity ✭✭
    edited March 2016

    @PatriciaRyan in Android, you can do this in the OnActivityResult method:

    </p> <pre><code> protected override void OnActivityResult (int requestCode, Result resultCode, Intent intent) { base.OnActivityResult (requestCode, resultCode, intent); bool braked = false; string path = ""; try { if (resultCode == Result.Ok) { paths = new List<string> (); if (intent != null) { ClipData clipData = intent.ClipData; if (clipData != null) { for (int i = 0; i < clipData.ItemCount; i++) { if (i > 19) { braked = true; break; } ClipData.Item item = clipData.GetItemAt (i); global::Android.Net.Uri uri = item.Uri; //In case you need image's absolute path path = GetPathToImage (uri); paths.Add (path); } } else { global::Android.Net.Uri uri = intent.Data; path = GetPathToImage(uri); paths.Add (path); } MessagingCenter.Send<IGestureListener, List<string>> (this, "ImagesPath", paths); if (braked == true) { // Toast.MakeText (Xamarin.Forms.Forms.Context, "Only the top 20 images will be uploaded", ToastLength.Long).Show (); } } } //Send the paths to forms } catch (Exception ex) { //Toast.MakeText (Xamarin.Forms.Forms.Context, "Unable to open, error:" + ex.ToString(), ToastLength.Long).Show (); } }

    </p> <pre><code> private string GetPathToImage(global::Android.Net.Uri uri) { string doc_id = ""; using (var c1 = ContentResolver.Query (uri, null, null, null, null)) { c1.MoveToFirst (); String document_id = c1.GetString (0); doc_id = document_id.Substring (document_id.LastIndexOf (":") + 1); } string path = null; // The projection contains the columns we want to return in our query. string selection = MediaStore.Images.Media.InterfaceConsts.Id + " =? "; using (var cursor = ManagedQuery(MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] {doc_id}, null)) { if (cursor == null) return path; var columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data); cursor.MoveToFirst(); path = cursor.GetString(columnIndex); } return path; }

  • DamienSawyerDamienSawyer AUMember

    Thanks for posting that Charlin :-)

  • Hi,
    I am working on xamarin.forms app. I am creating the app for android and iOS. I need to open the gallery and select multiple images from gallery of devices. How I can do this in xamarin.forms cross- platform that can work for both android and iOS instead of xamarin native code for android and ios.

    Thanks
    Deepa

  • AlexFredricksAlexFredricks USMember

    @Charlin,

    Thanks so much for the info.

    I had a few questions regarding how to wire this up all back up. I think I'm just not quite understanding how to show the images on xamarin forms now. I need to display the images coming from both Android and iOS. Any advice would be appreciated.

    1) In iOS, based on your example, I got the gallery to open and the images loaded as List but how how do I display that back from the iOS specific code in from DependencyService.Get().OpenGallery()?

    2) Is the above Android code in the dependency service as well?

  • CharlinCharlin DOUniversity ✭✭

    @SethDawson for display the images back on Forms, i use a messenger:

    MessagingCenter.Send<IGestureListener, List> (this, "ImagesPath", paths);

    Basically, in my class where i want to display the image i have this:

    MessagingCenter.Subscribe<IGestureListener, List> (this, "ImagesPath", (x, arguments) => {
    //Code in Forms here
    });

  • CharlinCharlin DOUniversity ✭✭

    @DeepaRishikesavan.9244 right now,specially for select multiple images the only way to do that is doing a Custom renderer in each platform. @JamesMontemagno has a plugin for select images from gallery, but it only allows you to select one image https://github.com/jamesmontemagno/MediaPlugin

  • JRolandrosJRolandros FRMember ✭✭

    @Charlin said:
    @SethDawson for display the images back on Forms, i use a messenger:

    MessagingCenter.Send<IGestureListener, List> (this, "ImagesPath", paths);

    Basically, in my class where i want to display the image i have this:

    MessagingCenter.Subscribe<IGestureListener, List> (this, "ImagesPath", (x, arguments) => {
    //Code in Forms here
    });

    Please I have tried to display photo with its gallery path and it didn't work. can you please post how did you manage this in Xaml or C#? It could be really helpful.

    Many thanks.

  • ntgnstntgnst TRMember

    helpbibi plsss

  • crashnnburncrashnnburn USMember

    @Charlin Hello, I've finished implementing the code for iOS, it opens up the gallery and all, but when I choose "Done" nothing happens. I have tried the following:

    var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;

    picker.Completion.ContinueWith(t => {

    if (t.IsCanceled || t.Exception != null) {
        // no pictures for you!
        Debug.WriteLine("clicked cancel");
        topController.DismissViewController(true,null);
    } 
    

    }

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

    topController.PresentViewController(picker, true, null);

    All I get is the console log of "clicked cancel" and that's it. All I want to do is close the page that just popped up.

    Any help is appreciated.

    Thanks!

  • CharlinCharlin DOUniversity ✭✭

    @crashnnburn it works for me

    public void OpenGallery()
    {
    var picker = ELCImagePickerViewController.Instance;
    picker.MaximumImagesCount = 15;

            List<string> paths;
            picker.Completion.ContinueWith(t =>
            {
                picker.BeginInvokeOnMainThread(() =>
                    {
                    //dismiss the picker
                    picker.DismissViewController(true, null);
    
                        if (t.IsCanceled || t.Exception != null)
                        {
                        }
                        else {
                            paths= new List<string>();
    
                            var items = t.Result as List<AssetResult>;
                            foreach (var item in items)
                            {
                                var path=Save(item.Image, item.Name);
                                paths.Add(path);
                            }
    
                            MessagingCenter.Send<IMessanger, List<string>>(this, "ImagesSelected", paths);
                        }
    
    
                    });
            });
            var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (topController.PresentedViewController != null)
            {
                topController = topController.PresentedViewController;
            }
    
    
            topController.PresentViewController(picker, true, null);
    
        }
    
  • crashnnburncrashnnburn USMember
    edited November 2016

    @Charlin Thank you so much for your response! It worked!
    Any idea how I can put the AssetResult into a ImageSource so I can display them in Xamarin Forms?

    Actually, which library are you using for Save(item.Image, item.Name); ?

  • CharlinCharlin DOUniversity ✭✭

    For display the asset path in Xamarin Forms, i have a Save method which basically save the path locally and return me a new path.

    string Save(UIImage image, string name) {

            var documentsDirectory = Environment.GetFolderPath
                                  (Environment.SpecialFolder.Personal);
            string jpgFilename = System.IO.Path.Combine(documentsDirectory, name); // hardcoded filename, overwritten each time
            NSData imgData = image.AsJPEG();
            NSError err = null;
            if (imgData.Save(jpgFilename, false, out err))
            {
                return jpgFilename;
            }
            else {
                Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
                return null;
            }
        }
    

    Also make sure to delete the path in one moment in your app (for don't full your local device memory)

    //For delete the paths
    void CleanPaths(List filePaths)
    {

                var documentsDirectory = Environment.GetFolderPath
                                  (Environment.SpecialFolder.Personal);
    
                if (Directory.Exists(documentsDirectory))
                {
    
                    foreach (var p in filePaths)
                    {
                        File.Delete(p);
                    }
    
                }
        }
    
  • crashnnburncrashnnburn USMember

    Thanks again @Charlin !! :smile:
    Worked as expected. I appreciate your time and effort in answering my questions, I hope this also helps other people for reference.

  • @Charlin said:
    @PatriciaRyan in Android, you can do this in the OnActivityResult method:

    </p> <pre><code> protected override void OnActivityResult (int requestCode, Result resultCode, Intent intent) { base.OnActivityResult (requestCode, resultCode, intent); bool braked = false; string path = ""; try { if (resultCode == Result.Ok) { paths = new List<string> (); if (intent != null) { ClipData clipData = intent.ClipData; if (clipData != null) { for (int i = 0; i < clipData.ItemCount; i++) { if (i > 19) { braked = true; break; } ClipData.Item item = clipData.GetItemAt (i); global::Android.Net.Uri uri = item.Uri; //In case you need image's absolute path path = GetPathToImage (uri); paths.Add (path); } } else { global::Android.Net.Uri uri = intent.Data; path = GetPathToImage(uri); paths.Add (path); } MessagingCenter.Send<IGestureListener, List<string>> (this, "ImagesPath", paths); if (braked == true) { // Toast.MakeText (Xamarin.Forms.Forms.Context, "Only the top 20 images will be uploaded", ToastLength.Long).Show (); } } } //Send the paths to forms } catch (Exception ex) { //Toast.MakeText (Xamarin.Forms.Forms.Context, "Unable to open, error:" + ex.ToString(), ToastLength.Long).Show (); } }

    </p> <pre><code> private string GetPathToImage(global::Android.Net.Uri uri) { string doc_id = ""; using (var c1 = ContentResolver.Query (uri, null, null, null, null)) { c1.MoveToFirst (); String document_id = c1.GetString (0); doc_id = document_id.Substring (document_id.LastIndexOf (":") + 1); } string path = null; // The projection contains the columns we want to return in our query. string selection = MediaStore.Images.Media.InterfaceConsts.Id + " =? "; using (var cursor = ManagedQuery(MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] {doc_id}, null)) { if (cursor == null) return path; var columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data); cursor.MoveToFirst(); path = cursor.GetString(columnIndex); } return path; }

    Hi Charlin,

    Can you please post the complete code, so that it would be help full for all.

  • Hi Charlin,

    Can you please share the model of IGestureListener and code of MessagingCenter.Subscribe in the View page of forms

  • Is there a chance of getting an example project? I'm not seeing how it all fits together.

  • Is there a chance of getting an example project? I'm not seeing how it all fits together.

  • AndrePraAndrePra USMember

    @Charlin I'm using the ELCImagePickerViewController and I can retrieve the list of AssetResult.
    In my app I need to access some additional information about images, such as the creation date. Any idea how to get this data?
    Thanks

  • Paradox235Paradox235 INMember

    @Charlin Thanks a lot Charlin. It worked after making a few changes.

  • Paradox235Paradox235 INMember

    @PrajwalDAlmeida.7290 Please check if the following solves your purpose.

    Send from MainActivity:
    MessagingCenter.Send<IOnGestureListener, List>(this, "yourString", paths);

    Subscribe part: (in forms )
    MessagingCenter.Subscribe<IOnGestureListener, List>(this, "yourString", (x, info) => {
    //Your code here;
    });

    Note: Since IGestureListener was throwing error I used the IOnGestureListener.

  • AlexFredricksAlexFredricks USMember
    edited April 18

    I wanted to follow up and say got it all working. I wanted to store the images as bytes so I can later submit them to a webservice. When I resize the images you may notice I use LocalStorage.ImageQualityPercent. That's a setting users can set to determine what quality of images they want to submit. That references Plugin.Settings class. I also use Plugin.Media to allow users to grab images via the camera. I just convert to a byte stream in that case.

    For iOS install the ECLImagePicker.


    PCL View

        public partial class PhotoUpload : ContentPage
        {
            List<byte[]> _images;  //Store Bytes of image
            public PhotoUpload()
                {
                InitializeComponent();
                 _images = new List<byte[]>();
    
                //Subscribe notification
                    MessagingCenter.Subscribe<App, List<byte[]>>((App)Xamarin.Forms.Application.Current, "ImagesSelected", (s, images) =>
                    {
                        foreach (byte[] image in images)
                        {
                                Image newImage = new Image();
                                newImage.Source = ImageSource.FromStream(() => new MemoryStream(image));
                                stackImages.Children.Add(newImage);  //Stacklayout that holds images
                                _images.Add(image);
                         }
                    });
            }
    
            protected override void OnDisappearing()
            {
                    base.OnDisappearing();
                    MessagingCenter.Unsubscribe<App, List<byte[]>>(this, "ImagesSelected");
            }
    
    //Button Event to select photo
        private void PickPhoto(object sender, EventArgs e)
            {
                DependencyService.Get<IMediaService>().OpenGallery();
            }
        }
    

    PCL Interface

    namespace (Project Name).Interfaces
    {
        public interface IMediaService
        {
            void OpenGallery();
    
        }
    }
    

    IOS Dependency Class

        using Foundation;
        using UIKit;
        using Xamarin.Forms;
        using (Project Name).Interfaces;
        using (Project Name).iOS.Dependency;  //You have to reference your MediaService
        using (Project Name).iOS.Helpers;
        using ELCImagePicker;
    
            [assembly: Xamarin.Forms.Dependency(typeof(MediaService))]
            namespace (Project Name).iOS.Dependency
            {
                public class MediaService : IMediaService
                {
    
                    public MediaService() { }
    
                    public void OpenGallery()
                    {
                        var picker = ELCImagePickerViewController.Create(15);
                        picker.MaximumImagesCount = 15;
    
                        picker.Completion.ContinueWith(t =>
                        {
                            picker.BeginInvokeOnMainThread(() =>
                            {
                                //dismiss the picker
                                picker.DismissViewController(true, null);
    
                                if (t.IsCanceled || t.Exception != null)
                                {
                                }
                                else
                                {
                                    List<byte[]> images = new List<byte[]>();
    
                                    var items = t.Result as List<AssetResult>;
                                    foreach (var item in items)
                                    {
                                        var path = ImageHelper.GetPathToImage(item.Image, item.Name);
                                        var imageBytes = ImageHelper.ImageToBinary(path);
                                        images.Add(imageBytes);
                                        CleanPath(path);
                                    }
    
                        //Send images back
                                    MessagingCenter.Send<App, List<byte[]>>((App)Xamarin.Forms.Application.Current, "ImagesSelected", images);
                                }
                            });
                        });
    
                        var topController = UIApplication.SharedApplication.KeyWindow.RootViewController;
                        while (topController.PresentedViewController != null)
                        {
                            topController = topController.PresentedViewController;
                        }
                        topController.PresentViewController(picker, true, null);
                    }
    
                    private void CleanPath(string file)
                    {
                        var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                        if (Directory.Exists(documentsDirectory))
                        {
                            File.Delete(file);
                        }
                    }
                }
            }
    

    IOS Image Helper Class

    using CoreGraphics;
    using Foundation;
    using UIKit;
    
    namespace (Project Name).iOS.Helpers
    {
        public static class ImageHelper
        {
    
            public static byte[] ImageToBinary(string imagePath)
            {
    
                FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[fileStream.Length];
                fileStream.Read(buffer, 0, (int)fileStream.Length);
                fileStream.Close();
                return buffer;
            }
    
            public static string GetPathToImage(UIImage image, string name)
            {
    
                var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                string jpgFilename = System.IO.Path.Combine(documentsDirectory, name); // hardcoded filename, overwritten each time
    
                //calculate new size
                var width = (image.CGImage.Width * LocalStorage.ImageQualityPercent);
                var height = (image.CGImage.Height * LocalStorage.ImageQualityPercent);
    
                //begin resizing image
                UIImage resizedImage = ResizeImageWithAspectRatio(image, width, height);
                NSData imgData = resizedImage.AsJPEG();
                NSError err = null;
                if (imgData.Save(jpgFilename, false, out err))
                {
                    return jpgFilename;
                }
                else
                {
                    return null;
                }
            }
    
            private static UIImage ResizeImageWithAspectRatio(UIImage sourceImage, float maxWidth, float maxHeight)
            {
                var sourceSize = sourceImage.Size;
                var maxResizeFactor = Math.Max(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
                if (maxResizeFactor > 1) return sourceImage;
                var width = maxResizeFactor * sourceSize.Width;
                var height = maxResizeFactor * sourceSize.Height;
                UIGraphics.BeginImageContext(new CGSize(width, height));
                sourceImage.Draw(new CGRect(0, 0, width, height));
                var resultImage = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                return resultImage;
            }
        }
    }
    

    Android - Put in Main Activity

    using Android.App;
    using Android.Content;
    using Android.Content.PM;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    using Android.Provider;
    using Android.Database;
    
    using Xamarin.Forms;
    using (Your Project).Droid.Helpers;
    
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
            int IMAGES_SELECTED = 200;  //Used to determine which service is being called - photoselection
    
     protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
            {
                base.OnActivityResult(requestCode, resultCode, data);
    
                if (requestCode == IMAGES_SELECTED && resultCode == Result.Ok)
                {
                    List<byte[]> images = new List<byte[]>();
    
                    if (data != null)
                    {
                        ClipData clipData = data.ClipData;
                        if (clipData != null)
                        {
                            for (int i = 0; i < clipData.ItemCount; i++)
                            {
                                ClipData.Item item = clipData.GetItemAt(i);
                                Android.Net.Uri uri = item.Uri;
                                var path = GetRealPathFromURI(uri);
                                var imageBytes = ImageHelper.ImageToBinary(path);
                                images.Add(imageBytes);
                            }
                        }
                        else
                        {
                            Android.Net.Uri uri = data.Data;
                            var path = GetRealPathFromURI(uri);
                            var imageBytes = ImageHelper.ImageToBinary(path);
                            images.Add(imageBytes);
                        }
    
                        MessagingCenter.Send<App, List<byte[]>>((App)Xamarin.Forms.Application.Current, "ImagesSelected", images);
                    }
                }
            }
    
    public String GetRealPathFromURI(Android.Net.Uri contentURI)
            {
                ICursor imageCursor = null;
                string fullPathToImage = "";
    
                imageCursor = ContentResolver.Query(contentURI, null, null, null, null);
                imageCursor.MoveToFirst();
                int idx = imageCursor.GetColumnIndex(MediaStore.Images.ImageColumns.Data);
    
                if(idx != -1)
                {
                    //This works for older devices
                    fullPathToImage = imageCursor.GetString(idx);
                }
                else
                {
                    //This works for newer devices
                    ICursor cursor = null;
                    var docID = DocumentsContract.GetDocumentId(contentURI);
                    var id = docID.Split(':')[1];
                    var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
                    var projections = new string[] { MediaStore.Images.ImageColumns.Data };
                    // Try internal storage first
                    cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
                    if (cursor.Count == 0)
                    {
                        // not found on internal storage, try external storage
                        cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
                    }
                    var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
                    cursor.MoveToFirst();
                    fullPathToImage = cursor.GetString(colData);
                }
                return fullPathToImage;
            }
    }
    

    Android Dependency Class

    using Android;
    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.Provider;
    
    using Xamarin.Forms;
    using (Your Project).Interfaces;
        using (Your Project).Droid.Dependency; //You have to reference your MediaService
    
        [assembly: Xamarin.Forms.Dependency(typeof(MediaService))]
        namespace (Your Project).Droid.Dependency
        {
            public class MediaService : Java.Lang.Object, IMediaService
            {
                int IMAGES_SELECTED = 200;
    
                public MediaService() { }
    
                public void OpenGallery()
                {
                    Toast.MakeText(Xamarin.Forms.Forms.Context, "Select a maximum of 15 images", ToastLength.Long).Show();
    
                    //var imageIntent = new Intent(Intent.ActionView, MediaStore.Images.Media.ExternalContentUri);
                    var imageIntent = new Intent(Intent.ActionPick);
                    imageIntent.SetType("image/*");
                    imageIntent.PutExtra(Intent.ExtraAllowMultiple, true);
                    imageIntent.SetAction(Intent.ActionGetContent);
    
                    ((Activity)Forms.Context).StartActivityForResult(Intent.CreateChooser(imageIntent, "Select photos"), IMAGES_SELECTED);
                }
            }
        }
    

    Android Image Helper Class

    using Android.App;
    using Android.Content;
    using Android.Content.PM;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.Provider;
    using Android.Database;
    using Android.Graphics;
    using Android.Media;
    
    using Xamarin.Forms;
    
    namespace (Your Project).Droid.Helpers
    {
        public static class ImageHelper
        {
    
            public static byte[] ImageToBinary(string imagePath)
            {
                byte[] imageBytes;
    
                var originalImage = BitmapFactory.DecodeFile(imagePath);
                var rotation = GetRotation(imagePath);
                var width = (originalImage.Width * LocalStorage.ImageQualityPercent);
                var height = (originalImage.Height * LocalStorage.ImageQualityPercent);
                var scaledImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, true);
    
                if (rotation != 0)
                {
                    var matrix = new Matrix();
                    matrix.PostRotate(rotation);
                    scaledImage = Bitmap.CreateBitmap(scaledImage, 0, 0, scaledImage.Width, scaledImage.Height, matrix, true);
                }
    
                using (var ms = new MemoryStream())
                {
                    scaledImage.Compress(Bitmap.CompressFormat.Jpeg, 90, ms);
                    imageBytes = ms.ToArray();
                }
    
                originalImage.Recycle();
                scaledImage.Recycle();
                originalImage.Dispose();
                scaledImage.Dispose();
                // Dispose of the Java side bitmap.
                GC.Collect();
    
                return imageBytes;
            }
    
            private static int GetRotation(string filePath)
            {
                using (var ei = new ExifInterface(filePath))
                {
                    var orientation = (Android.Media.Orientation)ei.GetAttributeInt(ExifInterface.TagOrientation, (int)Android.Media.Orientation.Normal);
    
                    switch (orientation)
                    {
                        case Android.Media.Orientation.Rotate90:
                            return 90;
                        case Android.Media.Orientation.Rotate180:
                            return 180;
                        case Android.Media.Orientation.Rotate270:
                            return 270;
                        default:
                            return 0;
                    }
                }
            }
        }
    }
    

    hope that helps

  • MakgaurMakgaur USMember ✭✭

    @Charlin said:
    @PatriciaRyan in Android, you can do this in the OnActivityResult method:

    </p> <pre><code> protected override void OnActivityResult (int requestCode, Result resultCode, Intent intent) { base.OnActivityResult (requestCode, resultCode, intent); bool braked = false; string path = ""; try { if (resultCode == Result.Ok) { paths = new List<string> (); if (intent != null) { ClipData clipData = intent.ClipData; if (clipData != null) { for (int i = 0; i < clipData.ItemCount; i++) { if (i > 19) { braked = true; break; } ClipData.Item item = clipData.GetItemAt (i); global::Android.Net.Uri uri = item.Uri; //In case you need image's absolute path path = GetPathToImage (uri); paths.Add (path); } } else { global::Android.Net.Uri uri = intent.Data; path = GetPathToImage(uri); paths.Add (path); } MessagingCenter.Send<IGestureListener, List<string>> (this, "ImagesPath", paths); if (braked == true) { // Toast.MakeText (Xamarin.Forms.Forms.Context, "Only the top 20 images will be uploaded", ToastLength.Long).Show (); } } } //Send the paths to forms } catch (Exception ex) { //Toast.MakeText (Xamarin.Forms.Forms.Context, "Unable to open, error:" + ex.ToString(), ToastLength.Long).Show (); } }

    </p> <pre><code> private string GetPathToImage(global::Android.Net.Uri uri) { string doc_id = ""; using (var c1 = ContentResolver.Query (uri, null, null, null, null)) { c1.MoveToFirst (); String document_id = c1.GetString (0); doc_id = document_id.Substring (document_id.LastIndexOf (":") + 1); } string path = null; // The projection contains the columns we want to return in our query. string selection = MediaStore.Images.Media.InterfaceConsts.Id + " =? "; using (var cursor = ManagedQuery(MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] {doc_id}, null)) { if (cursor == null) return path; var columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data); cursor.MoveToFirst(); path = cursor.GetString(columnIndex); } return path; }

    Correction
    var paths = new List ();
    &
    for (int i = 0; i < (clipData.ItemCount-1); i++) {

  • CarloArdito.4952CarloArdito.4952 USMember

    I have the error below in var docID = DocumentsContract.GetDocumentId(contentURI);
    {Java.Lang.IllegalArgumentException: Invalid URI: content://com.google.android.apps.photos.contentprovider/0/1/mediaKey%3A%2FAF1QipNWhfIcGuxE2rh8EJHfF3R2P_sRcZ6Y8Ad_U6up/ACTUAL/992029365...
    }

    Why ?

  • CharlinCharlin DOUniversity ✭✭

    I just write an article about this https://xamgirl.com/select-multiple-images-from-gallery-in-xamarin-forms/
    Hope that helps someone :)

  • wehweh USMember ✭✭

    I've been following this thread as I too need cross-platform, multi-pick capability.
    I've downloaded the ELCImagePicker for iOS - but have no idea how to install it!

    Can someone please tell me how to install the ELCImagePicker for VS 2017 (pc) ?

  • Hi,
    how to get longitude and latitude value in xamarin form UWP
    Already completed Android and Ios but i cant able to Complete on UWP
    please Help Me immediately

    thanks
    Sameer

  • hi,
    how to pick an image from gallery in xamarin forms UWP
    please help me guys...

  • SanjayTejaniSanjayTejani USMember ✭✭✭

    @Charlin

    I have seen your multiple photo upload code and i revive null from "ContentResolver.Query" can you please tell what should i have to change in my code or else other???

  • rakeshraghavanrakeshraghavan INMember ✭✭

    I am building an enterprise application .Since ELCImagePicker is License free version i can't use it. I implemented it in android without any plugin.Is there any other component in xamarin forms?.

Sign In or Register to comment.