如何将图像源(Image.Source)转换为字符串类型

11

在Xamarin中设置图片来源非常简单

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

但我不能进行反向操作。
例如:给定一个已设置源的图像,打印出该源。

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

请问如何通过字符串获取图片的源码。


1
什么是Image,以及哪种情况下读取属性无法工作?我还看到您使用source进行设置并使用Source进行读取 - 它们实际上是不同的属性吗,还是这是一个笔误?如果是笔误,请展示您实际尝试编译的代码。 - James Thorpe
第一个代码片段也不会起作用。假设您正在谈论System.Drawing.Image,那么没有公共的“source”属性。BCL公共成员名称从来不以小写字母开头。 - Asad Saeeduddin
@Asad:注意Xamarin标签。http://iosapi.xamarin.com/?link=T%3aXamarin.Forms.Image - Jeroen Vannevel
在 C# 中有几种“图像”类型,您指的是哪一种? - DividedByZero
Image是一个抽象类。你是指Bitmap吗? - Yuval Itzchakov
显示剩余2条评论
3个回答

22

Xamarin.FormsImage.Source属性类型为ImageSource

Xamarin.Forms中的ImageSource有几个继承该类的类,如下:

  • FileImageSource
  • StreamImageSource
  • UriImageSource

您可以对Image.Source进行类型检查,以查看在Image.Source中使用了哪种实现,然后强制转换并访问强制转换对象的属性。

例如(假设ImageSourceFileImageSource),则会得到以下结果:

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;
}

2
看起来 Xamarin.Forms.Image 有一个类型为 Xamarin.Forms.ImageSourceSource 属性,该属性从 string 隐式转换。这就是为什么你可以使用 Image.Source = "someImage.jpg",但是它没有办法回到原始状态,很可能是因为它只使用字符串查找文件并加载它。如果你需要已加载文件的名称,你将不得不自己跟踪它。

0
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");
        }
    }

或者像这样使用它

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

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接