通过 Web API 返回图像时出现问题

本文关键字:问题 图像 Web API 返回 通过 | 更新日期: 2023-09-27 17:55:34

我遇到了一个奇怪的问题,通过 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 字节,我确实尝试手动设置内容长度,但随后文件根本不下载。

通过 Web API 返回图像时出现问题

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

bitmapStream.Position = 0 ;