2012-01-30 117 views
3

我對Android和WCF都很新穎。我正在使用SQL Server數據庫中的一個非常小的圖像用戶表作爲varbinary。在我的服務,我有以下OperationContract的:Android從WCF Rest服務獲取圖片

 [OperationContract] 
    [WebGet(UriTemplate = "users/{emailAddress}/Image", ResponseFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Bare)] 
    System.IO.Stream GetImage(string emailAddress); 

實現:

 public System.IO.Stream GetImage(string emailAddress) 
    { 
     //parse personID, call DB 
     string query = "Select profilePic from Flows_Users WHERE emailAddress= @emailAddress"; 
     SqlConnection objConnection = new SqlConnection(); 

     DataSet ObjDataset = new DataSet(); 
     SqlDataAdapter objAdapater = new SqlDataAdapter(); 
     SqlCommand objCommand = new SqlCommand(query, objConnection); 
     objCommand.Parameters.Add("emailAddress", SqlDbType.NVarChar).Value = emailAddress; 
     objConnection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ToString(); 
     objConnection.Open(); 
     byte[] pic = (byte[])objCommand.ExecuteScalar(); 
     objConnection.Close(); 

     // if (pic == null) 
     //  return null; 

     OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse; 

     // //if (image_not_found_in_DB) 
     // //{ 
     // // context.StatusCode = System.Net.HttpStatusCode.Redirect; 
     // // context.Headers.Add(System.Net.HttpResponseHeader.Location, url_of_a_default_image); 
     // // return null; 
     // //} 

     //// everything is OK, so send image 

     context.Headers.Add(System.Net.HttpResponseHeader.CacheControl, "public"); 
     context.ContentType = "image/jpeg"; 
     // context.LastModified = date_image_was_stored_in_database; 
     context.StatusCode = System.Net.HttpStatusCode.OK; 
     return new System.IO.MemoryStream(pic); 
    } 

有沒有辦法讀入一個Android圖片看?我無法使用base64 JSON方式,因爲每次我嘗試將它放入JSONArray時,字符串都會終止。

任何幫助,將不勝感激,我一直在這個星期六以來的工作。

回答

0

您正在返回一個MemoryStream對象。改爲返回圖像的Base64編碼字節數組。

在Android端,您可以將其重新轉換爲圖像並將其放置在ImageView中。