Nanoc
Nanoc

Reputation: 2381

Microsoft Cognitive API Image Search

Im trying to use the Microsoft API of Bing image described here

I only want to use the image insights to find similar images by sending a image at the body of the post request, as the doc says i can provide a url or the image.

The image is being captured by a phone camera and sent to the api, the idea is to end up getting similar image results.

At first i was getting a error saying the 'q' parameter was required, but i do not want to use a search query just the image.

So i changed the ContentType to "multipart/form-data" and used "/search?modulesRequested=similarimages"

This seems to do something as now i dont get any error, the api response is just a empty string so im really lost here...

Heres my code to send the request.

        public async Task<string> GetImageInsights(byte[] image)
    {
        var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?modulesRequested=similarimages";

        var response = await RequestHelper.MakePostRequest(uri, new string(Encoding.UTF8.GetChars(image)), key, "multipart/form-data");

        var respString = await response.Content.ReadAsStringAsync();

        return respString;
    }
    public static async Task<HttpResponseMessage> MakePostRequest(string uri, string body, string key, string contentType)
    {
        var client = new HttpClient();

        // Request headers
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);

        // Request body
        byte[] byteData = Encoding.UTF8.GetBytes(body);

        using (var content = new ByteArrayContent(byteData))
        {
            content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
            return await client.PostAsync(uri, content);
        }
    }

Im using C# with Xamarin on Android

Upvotes: 0

Views: 387

Answers (1)

cthrash
cthrash

Reputation: 2973

For the service to work correctly, both a name and filename are required for the form part:

public async Task<string> GetImageInsights(byte[] image)
{
    var uri = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?modulesRequested=similarimages";

    var response = await RequestHelper.MakePostRequest(uri, image, key);

    var respString = await response.Content.ReadAsStringAsync();

    return respString;
}

class RequestHelper
{ 
    public static async Task<HttpResponseMessage> MakePostRequest(String uri, byte[] imageData, string key)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);

            var content = new MultipartFormDataContent();
            content.Add(new ByteArrayContent(imageData), "image", "image.png");

            return await client.PostAsync(uri, content);
        }
    }
}

Upvotes: 1

Related Questions