1

Face API works with URL of the image but when I try to send image as Base64 encoded it returns an error. In this sample code I used Restsharp to send the data

My code is like below.

 public string GenerateRest(String Base64Image)
    {
        var serviceURL = Constants.BaseServiceURI;
        var client = new RestClient(serviceURL);

        var request = new RestRequest(Constants.BaseResoruce, Method.POST);
        request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
        request.AddHeader("Content-Type", "application/octet-stream");

        request.RequestFormat = DataFormat.Json;

        var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);

        byte[] newBytes = Convert.FromBase64String(baseString);

        request.AddBody(newBytes);
        // execute the request
        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string

        return content;
    }

After fixing Restsharp request according to answer code is like

 public FaceAPIOutput GenerateRest(String Base64Image)
    {
        var serviceURL = Constants.BaseServiceURI;
        var client = new RestClient(serviceURL);
        var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);
        byte[] newBytes = Convert.FromBase64String(baseString);

        var request = new RestRequest(Constants.BaseResoruce, Method.POST);
        request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
        request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);
        request.RequestFormat = DataFormat.Json;

        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string

        return ConvertToFaceAPIOutObject(content);
    }
zapoo
  • 1,548
  • 3
  • 17
  • 32

1 Answers1

3

Restsharp looks a bit idiosyncratic when taking a binary payload. Instead of request.AddBody, which adds a multipart form section, you need to do the following:

request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);

c.f. Can RestSharp send binary data without using a multipart content type?

Community
  • 1
  • 1
cthrash
  • 2,938
  • 2
  • 11
  • 10