首页 > 解决方案 > 使用 ImageSource.FromUri 从 mvc 检索图像

问题描述

我有发布图像的 mvc web api。我正在尝试使用将图像检索到我的 xamarin 项目中ImageSource.FromUri

我完全能够在网站上查看此图像。但不在我的 xamarin 项目中。

我想知道我做错了什么。这是我的代码

发布图像的 API

   [HttpGet]
    [AllowAnonymous]
    public ActionResult GetImage(string imagePath)
    {
        var path = Path.Combine(Actions.ImageRootPath, imagePath);
        if (!System.IO.File.Exists(path))
            return new EmptyResult();

        var stream= System.IO.File.OpenRead(path);

        return File(stream, "image/png");
    }

xamarin xaml

    <Frame Style="{StaticResource FrameContainer}" WidthRequest="200" HeightRequest="150" CornerRadius="10" BorderColor="Transparent">
                        <StackLayout Orientation="Vertical">
                            <Image Source="{Binding Logo, Converter={StaticResource ImageSource}}" WidthRequest="200" />
                            <StackLayout  HorizontalOptions="CenterAndExpand" Style="{StaticResource Form}" Padding="10,0,0,0" Orientation="Vertical">
                                <Label Text="{Binding Name}" HorizontalOptions="Center" Style="{StaticResource Header}" />
                                <Label Text="{Binding TotalVideos}" IsVisible="{Binding TotalVideos, Converter={StaticResource StringNullOrEmpty}}" HorizontalOptions="Center" Style="{StaticResource UnderText}" />
                            </StackLayout>
                        </StackLayout>
                    </Frame>

ImageSource 转换器

    if (value is string && value != null && value.ToString().Length >= 4 && !value.ToString().Contains("http"))
    {
        byte[] Base64Stream = System.Convert.FromBase64String(value.ToString());
        var img = ImageSource.FromStream(() => new MemoryStream(Base64Stream));
        return img;
    }
    else if (value is string && !string.IsNullOrEmpty(value?.ToString() ?? "") && value.ToString().Contains("http"))
    {
        var uri = new Uri(value.ToString());

        return ImageSource.FromUri(uri);
        //var data = Helper.HttpHelper.GetImage(value.ToString());
        //return GetImage(key, data.ToArray());

    }
    else if (value is byte[])
    {
        return ImageSource.FromStream(() => new MemoryStream(value as byte[]));
    }
    return ImageSource.FromFile("NoImage.png");

我尝试过的工作,但我不喜欢

下面的代码可以工作,但我必须先使用 webclient 下载图像

    var data = Helper.HttpHelper.GetImage(value.ToString());
    return ImageSource.FromStream(() => new MemoryStream(data));

这是图片网址

http://youtubemanager.ddns.net/Youtube.Manager.API/Images/GetImage?imagePath=alen.toma%5Cc2e8bcaa-e258-453b-84c4-868d23b03848.png

标签: asp.net-mvcxamarin.forms

解决方案


推荐阅读