Android从WCF Rest服务获取图片
问题描述:
我对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时,字符串都会终止。
任何帮助,将不胜感激,我一直在这个星期六以来的工作。
答
您正在返回一个MemoryStream对象。改为返回图像的Base64编码字节数组。
在Android端,您可以将其重新转换为图像并将其放置在ImageView中。