2017-08-12 78 views
0
派位图从机器人到WCF服务
urlConnection = (HttpURLConnection) url.openConnection(); 

urlConnection.setRequestMethod("POST"); 

urlConnection.setRequestProperty("Content-Type", "application/json"); 
urlConnection.setDoInput(true); 
urlConnection.setDoOutput(true); 
urlConnection.connect(); 

//Create JSONObject 
JSONObject jsonParam = new JSONObject(); 
jsonParam.put("phone", getDiviceID()); 
jsonParam.put("location", getLocation()); 
jsonParam.put("image", convertToString(image)); 

OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); 
out.write(jsonParam.toString()); 
out.close(); 

WCF服务我怎样才能使用的JSONObject

[OperationContract] 
[WebInvoke(Method = "POST", 
      ResponseFormat = WebMessageFormat.Json, 
      UriTemplate = "sendplantimage", 
      RequestFormat = WebMessageFormat.Json, 
      BodyStyle = WebMessageBodyStyle.Wrapped)] 
string sendImageToServer(Plants plants); 

植物类

[DataContract] 
public class Plants 
{ 
    [DataMember] 
    public string phone { get; set; } 

    [DataMember] 
    public string location { get; set; } 

    [DataMember] 
    public DateTime date { get; set; } 

    [DataMember] 
    public string[] plantimage { get; set; } 

    [DataMember] 
    public string path { get; set; } 
} 

我怎么能收集流在实现类,而我路过厂对象在sendImageTOServer(植物植物)和植物中没有数据成员具有数据类型流,因为此处的服务不允许代码

+1

以Base64编码的字符串形式发送图像。一旦到达目的地,您需要对其进行解码。 – Barns

+0

但我如何在服务端获得图像 –

+0

您是否在控制WFC服务? – Barns

回答

0

我不知道你正在获取你的图像,所以让我们开始一个文件。

Bitmap bm = BitmapFactory.decodeFile("/dir/myImage.jpg"); 
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
byte[] b = baos.toByteArray(); 

// encode byteArray to Base64 string 
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT); 

现在您可以将编码后的字符串添加到您的参数中。

jsonParam.put("image", encodedImage); 

在你需要编码的字符串中的Base64转换为字节数组

byte[] bytesArray = Convert.FromBase64String(yourBase64EncodedString); 

然后将字节数组转换回图像的WCF的一面。

public Image byteArrayToImage(byte[] bytesArray) 
{ 
    Image img = null; 
    using (var ms = new MemoryStream(bytesArray)) 
    { 
     img = Image.FromStream(ms); 
    } 
    return img; 
}