Loebre
Loebre

Reputation: 672

How to get Image.Source as string

It's easy to set a source for an image in Xamarin:

using Xamarin.Forms;
Image image = new Image;
image.Source = "someImage.jpg";

But I can not do the reverse operation.
ex: given an image with its source already set, print the source.

Console.WriteLine ("Print Image source ==> {0}",image.Source);
Console.WriteLine ("Print Image source ==> {0}",image.Source.ToString());

... and a few more incoherent combinations.

Could anyone tell me how to get the source (with a string) from an image.

Upvotes: 11

Views: 11238

Answers (3)

husham1414
husham1414

Reputation: 61

private async void myImage_Tapped(object sender, EventArgs e)
    {
        try
        {
            var url = ((sender as Image).Source as UriImageSource).Uri.AbsoluteUri;
            await Navigation.PushPopupAsync(new WebView_Page(url));
        }
        catch (Exception ex)
        {
            //await DisplayAlert("!", ex.Message, "OK");
        }
    }

or use it like

var url = (myImage.Source as UriImageSource).Uri.AbsoluteUri;

Upvotes: 0

Pete
Pete

Reputation: 4746

The Xamarin.Forms Image.Source property is of type ImageSource.

ImageSource in Xamarin.Forms has a few classes that inherit this class such as:-

  • FileImageSource
  • StreamImageSource
  • UriImageSource

You can type check the Image.Source to see what implementation is being used in Image.Source, and then cast it, and access the properties of the casted object.

For instance (assuming ImageSource is a FileImageSource) you will have something like:-

Xamarin.Forms.Image objImage;
..
..

..
if (objImage.Source is Xamarin.Forms.FileImageSource)
{
    Xamarin.Forms.FileImageSource objFileImageSource = (Xamarin.Forms.FileImageSource)objImage.Source;
    //
    // Access the file that was specified:-
    string strFileName = objFileImageSource.File;
}

Upvotes: 22

juharr
juharr

Reputation: 32266

It looks like Xamarin.Forms.Image has a Source property of type Xamarin.Forms.ImageSource which has an implicit cast from string. That's why you can do Image.Source = "someImage.jpg", but it does not have a way to go back, likely because it only uses the string to find the file and load it. If you need the name of the file you loaded you'll have to keep track of it on your own.

Upvotes: 2

Related Questions