我在一个目录中有 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 代码,但我仍然一无所获 =/
最佳答案
如果你只返回一个内存流不容易区分流中的一个图像和另一个图像,而不是这个,你可以返回一个字节数组列表,然后你可以访问数组中的每个位置并从字节数组转换图像...
这是一个功能齐全的 dotnet 核心 webapi Controller :
public class GetImagesController : Controller
{
private readonly IWebHostEnvironment _host;
public GetImagesController(IWebHostEnvironment host)
{
_host = host;
}
[HttpGet("{images}")]
public async Task<List<byte[]>> Get([FromQuery]string images)
{
List<byte[]> imageBytes = new List<byte[]>();
String[] strArray = images.Split(',');
for (int i = 0; i < strArray.Length; i++)
{
String filePath = Path.Combine(_host.ContentRootPath, "images", strArray[i]+".jpg");
byte[] bytes = System.IO.File.ReadAllBytes(filePath);
imageBytes.Add(bytes);
}
return imageBytes;
}
}
这个 Controller 可以这样调用:
https://localhost:44386/getImages?images=P1,P2,P3
假设您的 ContentRooPath 下有一个名为 images 的文件夹,其中包含文件 P1.jpg、P2.jpg 和 P3.jpg。
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host?view=aspnetcore-3.0
关于c# - MVC WebAPI 返回多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58439227/