通过web api发出返回图像

时间:2014-03-30 15:39:51

标签: c# asp.net asp.net-web-api

我有一个奇怪的问题,通过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字节,我尝试手动设置内容长度但是然后该文件根本没有下载。

1 个答案:

答案 0 :(得分:5)

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

bitmapStream.Position = 0;