/
BingGetSimilarImages.cs
155 lines (134 loc) · 5.54 KB
/
BingGetSimilarImages.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//Copyright (c) Microsoft Corporation. All rights reserved.
//Licensed under the MIT License.
//This code allows you to upload a binary image and returns images similar to the one that is uploaded
//For more information about this sample, see the following documentation:
// https://docs.microsoft.com/en-us/azure/cognitive-services/bing-image-search/tutorial-image-post
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace ConsoleAppPostImage
{
// This sample uploads an image file for insights obtained from the Bing Image Search endpoint.
// For more information, see https://docs.microsoft.com/en-us/azure/cognitive-services/bing-image-search/tutorial-image-post
class Program
{
// Replace the accessKey string value with your valid access key.
const string accessKey = "ACCESS-KEY-STRING";
// The endpoint URI.
const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/images/details";
// The image to upload. Replace with your file and path.
const string imageFile = @"C:\Users\YOUR-IMAGE-FILE.jpg";
// Used to return image results including relevant headers
struct SearchResult
{
public String jsonResult;
public Dictionary<String, String> relevantHeaders;
}
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
if (accessKey.Length == 32)
{
//Console.WriteLine("Searching images for: " + searchTerm);
SearchResult result = BingImageSearch(uriBase);
Console.WriteLine("\nRelevant HTTP Headers:\n");
foreach (var header in result.relevantHeaders)
Console.WriteLine(header.Key + ": " + header.Value);
Console.WriteLine("\nJSON Response:\n");
Console.WriteLine(JsonPrettyPrint(result.jsonResult));
}
else
{
Console.WriteLine("Invalid Bing Search API subscription key!");
Console.WriteLine("Please paste yours into the source code.");
}
Console.Write("\nPress Enter to exit ");
Console.ReadLine();
}
/// <summary>
/// Performs a Bing Image search and return the results as a SearchResult.
/// </summary>
static SearchResult BingImageSearch(string uriStr)
{
WebClient client = new WebClient();
client.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
client.Headers["ContentType"] = "multipart/form-data";
byte[] resp = client.UploadFile(uriBase + "?modules=SimilarImages", imageFile);
var json = System.Text.Encoding.Default.GetString(resp);
// Create result object for return
var searchResult = new SearchResult()
{
jsonResult = json,
relevantHeaders = new Dictionary<String, String>()
};
return searchResult;
}
/// <summary>
/// Formats the given JSON string by adding line breaks and indents.
/// </summary>
/// <param name="json">The raw JSON string to format.</param>
/// <returns>The formatted JSON string.</returns>
static string JsonPrettyPrint(string json)
{
if (string.IsNullOrEmpty(json))
return string.Empty;
json = json.Replace(Environment.NewLine, "").Replace("\t", "");
StringBuilder sb = new StringBuilder();
bool quote = false;
bool ignore = false;
char last = ' ';
int offset = 0;
int indentLength = 2;
foreach (char ch in json)
{
switch (ch)
{
case '"':
if (!ignore) quote = !quote;
break;
case '\\':
if (quote && last != '\\') ignore = true;
break;
}
if (quote)
{
sb.Append(ch);
if (last == '\\' && ignore) ignore = false;
}
else
{
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
sb.Append(Environment.NewLine);
sb.Append(new string(' ', ++offset * indentLength));
break;
case '}':
case ']':
sb.Append(Environment.NewLine);
sb.Append(new string(' ', --offset * indentLength));
sb.Append(ch);
break;
case ',':
sb.Append(ch);
sb.Append(Environment.NewLine);
sb.Append(new string(' ', offset * indentLength));
break;
case ':':
sb.Append(ch);
sb.Append(' ');
break;
default:
if (quote || ch != ' ') sb.Append(ch);
break;
}
}
last = ch;
}
return sb.ToString().Trim();
}
}
}