Articles in this section
Category / Section

How to Load an Image from Gallery in ImageEditor Xamarin.Android

2 mins read

How to Load an Image from Gallery in ImageEditor Xamarin.Android?

Description:

This article explains you to load an Image from Gallery to the Image Editor.

 

Solution:

  1. Create a Xamarin application and initialize SfImageEditor control in it by using the below code.

 

Import the SfImageEditor as shown below,

 

 

 

using Syncfusion.SfImageEditor.Android;

 

 

C#

 

static Intent mainIntent;

private static int SELECT_FROM_GALLERY = 0;

internal static string Path { get; set; }

SfImageEditor editor;

 

protected override void OnCreate(Bundle bundle)

{

    base.OnCreate(bundle);

    editor = new SfImageEditor(this);

    SetContentView(editor);

 

}

 

  1. Load an Image from Gallery to the image editor by call the InitializeMediaPicker method as shown in below.

 

 

C#

 

public void InitializeMediaPicker()
{
    Intent = new Intent();
    Intent.SetType("image/*");
    Intent.SetAction(Intent.ActionGetContent);
    StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), SELECT_FROM_GALLERY);
}

 

 

 

 

 

private string GetPathToImage(Android.Net.Uri uri)
{
    string imgId = "";
    using (var c1 = ContentResolver.Query(uri, null, null, null, null))
    {
        c1.MoveToFirst();
        string imageId = c1.GetString(0);
        imgId = imageId.Substring(imageId.LastIndexOf(":") + 1);
    }
 
    string path = null;
 
    string selection = MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
    using (var cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] { imgId }, null))
    {
        if (cursor == null) return path;
        var columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.Media.InterfaceConsts.Data);
        cursor.MoveToFirst();
        path = cursor.GetString(columnIndex);
    }
    return path;
}

 

 

  1. Set the Captured image from Camera to the ImageEditor as Bitmap Only. So you need to set the Bitmap as shown in below

 

protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
    if (data == null) data = mainIntent;
    if ((resultCode != Result.Ok) || (data == null))
    {
        return;
    }
    if (resultCode == Result.Ok)
    {
        var uri = data.Data;
 
        if (requestCode == SELECT_FROM_GALLERY)
        {
            try
            {
                Path = GetPathToImage(uri);
                editor.Bitmap = BitmapFactory.DecodeFile(Path);
 
            }
            catch (Exception ex)
            {
 
            }
        }
 
        else return;
    }
}

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied