gpt4 book ai didi

c# - 通过 Web api 返回图像的问题

转载 作者:行者123 更新时间:2023-12-02 21:29:15 25 4
gpt4 key购买 nike

我在通过 Web api 返回图像时遇到了一个奇怪的问题,我在应用程序中的多个地方都执行了此操作,但没有失败,但这一个导致了我的问题,任何帮助将不胜感激。

这有效

  Bitmap bitmap = getImage();
MemoryStream bitmapStream = new MemoryStream();
bitmap.Save("C:\\test.png", System.Drawing.Imaging.ImageFormat.Png);

if (bitmap != null)
{
if (Request.Headers.IfModifiedSince.HasValue)
{
// The file has not been modified since the browser cached it.
return new HttpResponseMessage(HttpStatusCode.NotModified);
}
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream("C:\\test.png", FileMode.Open));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return response;
}
else
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}

虽然这不是

 Bitmap bitmap = getImage();
MemoryStream bitmapStream = new MemoryStream();
bitmap.Save(bitmapStream, System.Drawing.Imaging.ImageFormat.Png);

if (bitmap != null)
{
if (Request.Headers.IfModifiedSince.HasValue)
{
// The file has not been modified since the browser cached it.
return new HttpResponseMessage(HttpStatusCode.NotModified);
}
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(bitmapStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return response;
}
else
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}

我确实需要在内存中执行此操作,而不是将临时文件保存到驱动器中,但由于某种原因,当我在内存中执行此操作时,结果是一个空文件 0 字节,我确实尝试手动设置内容长度,但随后该文件根本无法下载。

最佳答案

保存后您需要重置流的位置。

bitmapStream.Position = 0;

关于c# - 通过 Web api 返回图像的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22745984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com