2014-03-30 107 views
2

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

回答

5

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

bitmapStream.Position = 0;