【问题标题】:Loading Images from Web Api in Xamarin.Forms从 Xamarin.Forms 中的 Web Api 加载图像
【发布时间】:2016-06-25 18:12:08
【问题描述】:

我需要将图片从 Web api 后端加载到我的 Xamarin.Forms 应用程序中。 图片存储在 Azure Blob 存储中。

这是我的 Web Api 方法:

[HttpGet("{id}")]
public HttpResponseMessage Get(int id)
{
    // Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("ConnectionString");

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference("picturecontainer");

    // Retrieve reference to a blob named "photo.jpg".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("picture");

    var stream = new MemoryStream();

    blockBlob.DownloadToStream(stream);

    Image image = Image.FromStream(stream);
    MemoryStream memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Jpeg);

    HttpResponseMessage result = new    HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(memoryStream.ToArray());

    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

    return result;
}

在我的应用中,我尝试使用以下代码下载图像字节:

public App ()
{
    _client = new HttpClient();
    _client.MaxResponseContentBufferSize = 256000;

    Button downloadImageBtn = new Button () {
        Text = "Download Image",
    };
    var image = new Image() {
        Source = ImageSource.FromUri (new Uri ("http://www.engraversnetwork.com/files/placeholder.jpg")),
        Aspect = Aspect.AspectFit
    };
    downloadImageBtn.Clicked += async (object sender, EventArgs e) => {
        var values = await handleClick (sender, e);
        uploadPicButton.Text = values;
        var imageBytes = await downloadPicture();
        image.Source = ImageSource.FromStream(() => new MemoryStream(imageBytes));
    };

    MainPage = new ContentPage {
        Content = new StackLayout {
            VerticalOptions = LayoutOptions.Center,
            Children = {
                image,
                downloadImageBtn
            }
        }
    };
}

private async Task<byte[]> downloadPicture()
{
    var uri = new Uri (string.Format (RestUrl, "5"));
    //return await _client.GetByteArrayAsync (uri);
    var response = await _client.GetAsync (uri);
    if (response.IsSuccessStatusCode) {
        var content = await response.Content.ReadAsByteArrayAsync ();
        return content;
    }
    throw new HttpRequestException ();
}

但是,当我单击按钮时,占位符图像消失了。 从服务器发送图片或在应用中接收图片时是否有问题?

【问题讨论】:

  • 你没有显示downloadPicture的代码,所以不知道是不是这个函数内部的问题。尝试调试。在获得 imageBytes 后放置一个断点。有多少字节?它是空的还是空的?是否与您的图片大小相符?
  • @Grisha 我在问题中添加了downloadPicture() 代码。但是,从服务器发送图片时,内容正文大约有 170k 字节,但返回的图像只有 265 个字节。
  • 好的,我们更接近了。现在检查服务器端,在 Get 函数中,您发送了多少字节。检查结果。内容。
  • @Grisha 就像我在上一条评论中所说,result.Content int Get 函数的大小约为 170k 字节

标签: image azure asp.net-web-api xamarin-forms azure-blob-storage


【解决方案1】:

我不会手动下载图片。

如果您想加载更多图像和/或允许在加载时显示占位符,我推荐FFImageLoading 库。它提供了很好的功能,例如下载、缓存、显示占位符和错误图像,最重要的是:将图像下采样到目标大小。这对android来说总是一个痛苦。它可用于本机 UI xamarin 项目和 Xamarin.Froms。

您可以将包含 url 的字符串直接绑定到 Source。代码如下:

<ffimageloading:CachedImage 
    Source="http://thecatapi.com/?id=MTQ5MzcyNA">
</ffimageloading:CachedImage>

【讨论】:

    【解决方案2】:

    在 blockblob.DownloadToStream 行之后,尝试将流的位置设置为 0。我不熟悉 Azure API,但我认为它可能会有所帮助。

    另外,请尝试在您的 downloadPicture 函数中使用 ReadAsStreamAsync 而不是 ReadAsByteArrayAsync。像这样的:

    var responseStream = await response.Content.ReadAsStreamAsync();
    byte[] buf = new byte[512];
    int bufSize;
    while((bufSize = (await responseStream.ReadAsync(buf, 0, buf.Length))) > 0)
    {
        // store the received bytes to some buffer until the file is fully downloaded
    }
    

    您是否通过这种方式获取所有内容?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多