Mubbshar Anwar
Mubbshar Anwar

Reputation: 21

How can i send Bitmap from android to WCF service using JsonObject

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 service

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

Plant Class

[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; }
}

How can i collect Stream in implementation class while i am passing plant object in sendImageTOServer(Plants plants) and plant have no data member that have data type Stream because service do not allow code here

Upvotes: 2

Views: 201

Answers (1)

Barns
Barns

Reputation: 4849

I don't know you are getting your image so lets just start with a file.

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);

Now you can add the encoded string to your parameters.

jsonParam.put("image", encodedImage);

On the WCF side you need to convert the base64 encoded string into a byte array

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

Then convert the byte array back into an image.

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

Upvotes: 1

Related Questions