【发布时间】:2019-10-18 22:10:24
【问题描述】:
我在一个目录中有 3 张图片,但我的代码总是返回其中一张。我想返回 3 张图片 image1.jpg、image2.jpg、image3.jpg 并将它们放入我的 Xamarin 应用程序中。
我认为像数组一样返回结果可能会解决问题,但我不明白我需要什么。
var result = new HttpResponseMessage(HttpStatusCode.OK);
MemoryStream ms = new MemoryStream();
for (int i = 0; i < 3; i++)
{
String filePath = HostingEnvironment.MapPath("~/Fotos/Empresas/Comer/" + id + (i + 1) + ".jpg");
FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate);
Image image = Image.FromStream(fileStream);
image.Save(ms, ImageFormat.Jpeg);
fileStream.Close();
byte[] bytes = File.ReadAllBytes(filePath);
byte[] length = BitConverter.GetBytes(bytes.Length);
// Write length followed by file bytes to stream
ms.Write(length, 0, 3);
ms.Write(bytes, 0, bytes.Length);
}
result.Content = new StreamContent(ms);
return result;
现在我得到字节,我现在编辑一点代码
byte[] imageAsBytes = client.GetByteArrayAsync(url).Result;
MemoryStream stream1 = new MemoryStream(imageAsBytes);
img.Source = ImageSource.FromStream(() => { return stream1; });
这是我获取图像的 xamarin 代码,但我仍然一无所获 =/
【问题讨论】:
-
考虑返回一个包含 3 字节数组的对象。使用 File.ReadAllBytes() 将整个图像文件读入服务器端的字节数组。前端 Xamarin 客户端必须将每个字节数组转换为图像。一个警告是 WebAPI 调用返回的总字节数是有限制的。
-
result.Content = new ByteArrayContent(memoryStream.ToArray());每次循环都会覆盖 result.Content 的当前值。我希望它在每次调用时返回最后处理的图像。
-
我认为我在 xamarin 中的方式有误,我将在编辑中显示我转换字节的方式
标签: c# asp.net-mvc