The Bing Visual Search API returns information about an image that you provide. In this tutorial we will create a simple console application, that sends a Bing Visual Search API request and displays the JSON search results.
Create a new Console solution in Visual Studio 2017.
Add the following code in the Program.cs
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;
namespace BingVisualSearch
{
class Program
{
// Replace the accessKey string value with your valid subscription key.
const string accessKey = "<SubscriptionKey>";
const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/images/visualsearch";
// Set the path to the image that you want to get insights of.
static string imagePath = @"<ImagePath>";
// Boundary strings for form data in body of POST.
const string CRLF = "\r\n";
static string BoundaryTemplate = "batch_{0}";
static string StartBoundaryTemplate = "--{0}";
static string EndBoundaryTemplate = "--{0}--";
const string CONTENT_TYPE_HEADER_PARAMS = "multipart/form-data; boundary={0}";
const string POST_BODY_DISPOSITION_HEADER = "Content-Disposition: form-data; name=\"image\"; filename=\"{0}\"" + CRLF +CRLF;
static void Main()
{
try
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
if (accessKey.Length == 32)
{
if (IsImagePathSet(imagePath))
{
var filename = GetImageFileName(imagePath);
Console.WriteLine("Getting image insights for image: " + filename);
var imageBinary = GetImageBinary(imagePath);
// Set up POST body.
var boundary = string.Format(BoundaryTemplate, Guid.NewGuid());
var startFormData = BuildFormDataStart(boundary, filename);
var endFormData = BuildFormDataEnd(boundary);
var contentTypeHdrValue = string.Format(CONTENT_TYPE_HEADER_PARAMS, boundary);
var json = BingImageSearch(startFormData, endFormData, imageBinary, contentTypeHdrValue);
Console.WriteLine("\nJSON Response:\n");
Console.WriteLine(json);
}
}
else
{
Console.WriteLine("Invalid Bing Visual Search API subscription key!");
Console.WriteLine("Please paste yours into the source code.");
}
Console.Write("\nPress Enter to exit ");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Verify that imagePath exists.
/// </summary>
static Boolean IsImagePathSet(string path)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentException("Image path is null or empty.");
if (!File.Exists(path))
throw new ArgumentException("Image path does not exist.");
var size = new FileInfo(path).Length;
if (size > 1000000)
throw new ArgumentException("Image is greater than the 1 MB maximum size.");
return true;
}
/// <summary>
/// Get the binary characters of an image.
/// </summary>
static byte[] GetImageBinary(string path)
{
return File.ReadAllBytes(path);
}
/// <summary>
/// Get the image's filename.
/// </summary>
static string GetImageFileName(string path)
{
return new FileInfo(path).Name;
}
/// <summary>
/// Build the beginning part of the form data.
/// </summary>
static string BuildFormDataStart(string boundary, string filename)
{
var startBoundary = string.Format(StartBoundaryTemplate, boundary);
var requestBody = startBoundary + CRLF;
requestBody += string.Format(POST_BODY_DISPOSITION_HEADER, filename);
return requestBody;
}
/// <summary>
/// Build the ending part of the form data.
/// </summary>
static string BuildFormDataEnd(string boundary)
{
return CRLF + CRLF + string.Format(EndBoundaryTemplate, boundary) + CRLF;
}
/// <summary>
/// Calls the Bing visual search endpoint and returns the JSON response.
/// </summary>
static string BingImageSearch(string startFormData, string endFormData, byte[] image, string contentTypeValue)
{
WebRequest request = HttpWebRequest.Create(uriBase);
request.ContentType = contentTypeValue;
request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
request.Method = "POST";
// Writes the boundary and Content-Disposition header, then writes
// the image binary, and finishes by writing the closing boundary.
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(startFormData);
writer.Flush();
requestStream.Write(image, 0, image.Length);
writer.Write(endFormData);
writer.Flush();
writer.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
return json;
}
}
}
usingSystem;
usingSystem.Text;
usingSystem.Net;
usingSystem.IO;
usingSystem.Collections.Generic;
namespace BingVisualSearch
{
class Program
{
// Replace the accessKey string value with your valid subscription key.
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;
namespace BingVisualSearch
{
class Program
{
// Replace the accessKey string value with your valid subscription key.
const string accessKey = "<SubscriptionKey>";
const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/images/visualsearch";
// Set the path to the image that you want to get insights of.
static string imagePath = @"<ImagePath>";
// Boundary strings for form data in body of POST.
const string CRLF = "\r\n";
static string BoundaryTemplate = "batch_{0}";
static string StartBoundaryTemplate = "--{0}";
static string EndBoundaryTemplate = "--{0}--";
const string CONTENT_TYPE_HEADER_PARAMS = "multipart/form-data; boundary={0}";
const string POST_BODY_DISPOSITION_HEADER = "Content-Disposition: form-data; name=\"image\"; filename=\"{0}\"" + CRLF +CRLF;
static void Main()
{
try
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
if (accessKey.Length == 32)
{
if (IsImagePathSet(imagePath))
{
var filename = GetImageFileName(imagePath);
Console.WriteLine("Getting image insights for image: " + filename);
var imageBinary = GetImageBinary(imagePath);
// Set up POST body.
var boundary = string.Format(BoundaryTemplate, Guid.NewGuid());
var startFormData = BuildFormDataStart(boundary, filename);
var endFormData = BuildFormDataEnd(boundary);
var contentTypeHdrValue = string.Format(CONTENT_TYPE_HEADER_PARAMS, boundary);
var json = BingImageSearch(startFormData, endFormData, imageBinary, contentTypeHdrValue);
Console.WriteLine("\nJSON Response:\n");
Console.WriteLine(json);
}
}
else
{
Console.WriteLine("Invalid Bing Visual Search API subscription key!");
Console.WriteLine("Please paste yours into the source code.");
}
Console.Write("\nPress Enter to exit ");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Verify that imagePath exists.
/// </summary>
static Boolean IsImagePathSet(string path)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentException("Image path is null or empty.");
if (!File.Exists(path))
throw new ArgumentException("Image path does not exist.");
var size = new FileInfo(path).Length;
if (size > 1000000)
throw new ArgumentException("Image is greater than the 1 MB maximum size.");
return true;
}
/// <summary>
/// Get the binary characters of an image.
/// </summary>
static byte[] GetImageBinary(string path)
{
return File.ReadAllBytes(path);
}
/// <summary>
/// Get the image's filename.
/// </summary>
static string GetImageFileName(string path)
{
return new FileInfo(path).Name;
}
/// <summary>
/// Build the beginning part of the form data.
/// </summary>
static string BuildFormDataStart(string boundary, string filename)
{
var startBoundary = string.Format(StartBoundaryTemplate, boundary);
var requestBody = startBoundary + CRLF;
requestBody += string.Format(POST_BODY_DISPOSITION_HEADER, filename);
return requestBody;
}
/// <summary>
/// Build the ending part of the form data.
/// </summary>
static string BuildFormDataEnd(string boundary)
{
return CRLF + CRLF + string.Format(EndBoundaryTemplate, boundary) + CRLF;
}
/// <summary>
/// Calls the Bing visual search endpoint and returns the JSON response.
/// </summary>
static string BingImageSearch(string startFormData, string endFormData, byte[] image, string contentTypeValue)
{
WebRequest request = HttpWebRequest.Create(uriBase);
request.ContentType = contentTypeValue;
request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
request.Method = "POST";
// Writes the boundary and Content-Disposition header, then writes
// the image binary, and finishes by writing the closing boundary.
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(startFormData);
writer.Flush();
requestStream.Write(image, 0, image.Length);
writer.Write(endFormData);
writer.Flush();
writer.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();
return json;
}
}
}
Replace the accessKey value with your subscription key and the imagePath value with the path of the image to upload in the above code.
Run the program to get the results. The JSON result looks like the following code snippet:
Georgia Kalyva is a Microsoft AI MVP with years of experience in software engineering and is currently working for ITT as Web Applications Developer. She is passionate about AI and Azure and has represented Greece in global competitions in Technology and Entrepreneurship. She is also a member of the Microsoft Student Partners team and has taken over the role of mentor in several Microsoft competitions and trainings.
Hmm it appears like your site ate my first comment (it was super
long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your
blog. I as well am an aspiring blog writer but I’m still new to the whole thing.
Do you have any suggestions for newbie blog writers?
I’d certainly appreciate it.
Hmm it appears like your site ate my first comment (it was super
long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your
blog. I as well am an aspiring blog writer but I’m still new to the whole thing.
Do you have any suggestions for newbie blog writers?
I’d certainly appreciate it.
Great Code.
I tried and it worked. Thanks