2014-03-30 102 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;