【发布时间】: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.ContentintGet函数的大小约为 170k 字节
标签: image azure asp.net-web-api xamarin-forms azure-blob-storage