//search celebrity photo with Azur Bing Image Search public void SearchCelebImage(string celebrityResult) { //Azure Conginitive Services CClone Subscription Key string subscriptionKey = "32dcbd11530d42b69bedde7961c05e5a"; //Save image result here Images imageResults = null; var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey)); //Find results and set here. imageResults = client.Images.SearchAsync(query: celebrityResult).Result; //search query if (imageResults != null) { var firstImageResult = imageResults.Value.First(); var lastImageResult = imageResults.Value.Last(); celebImage.Source = lastImageResult.ContentUrl; Console.WriteLine($"URL to the first image:\n\n {firstImageResult.ContentUrl}\n"); try { celebImage.Source = firstImageResult.ContentUrl; } catch { celebImage.Source = lastImageResult.ContentUrl; } } StopLoadingAnimation(); }
// Given a description and filepath, converts a description into a full size image public static void DownloadImageFromDescription(string description, string filePath) { var client = new ImageSearchClient(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(SearchSubscriptionKey)); var imageresults = client.Images.SearchAsync(description).Result; string url = imageresults.Value.ElementAt(new Random().Next(imageresults.Value.Count)).ContentUrl; using (WebClient webClient = new WebClient()) { byte[] data = webClient.DownloadData(new Uri(url)); using (MemoryStream mem = new MemoryStream(data)) { using (var newImage = Image.FromStream(mem)) { switch (Path.GetExtension(filePath).ToLower()) { case ".jpg": newImage.Save(filePath, ImageFormat.Jpeg); break; case ".png": newImage.Save(filePath, ImageFormat.Png); break; } } } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); var appSettings = Configuration.GetSection(nameof(AppSettings)).Get <AppSettings>(); services.AddScoped <IComputerVisionClient, ComputerVisionClient>(sp => { var client = new ComputerVisionClient(new Microsoft.Azure.CognitiveServices.Vision.ComputerVision.ApiKeyServiceClientCredentials(appSettings.VisionSubscriptionKey)) { Endpoint = appSettings.VisionEndpoint }; return(client); }); services.AddScoped <IImageSearchClient, ImageSearchClient>(sp => { var client = new ImageSearchClient(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(appSettings.BingSubscriptionKey)) { Endpoint = appSettings.VisionEndpoint }; return(client); }); services.AddScoped <IVisionSearchClient, VisionSearchClient>(); }
public async Task <List <Destination> > GetDestinationData(string destination) { if (MockDataStore.DestinationSearchCache.ContainsKey(destination)) { return(MockDataStore.DestinationSearchCache[destination]); } var client = new ImageSearchClient( new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials( ApiKeys.BingImageSearch)); var imageResult = await client.Images.SearchAsync($"{destination} attractions", minWidth : 500, minHeight : 500, imageType : "Photo", license : "Public", count : 10, maxHeight : 1200, maxWidth : 1200); var resultDestinations = new List <Destination>(); foreach (var imageResultItem in imageResult.Value) { resultDestinations.Add(new Destination { Title = destination, ImageUrl = imageResultItem.ContentUrl, MoreInfoUrl = imageResultItem.HostPageUrl }); } MockDataStore.DestinationSearchCache.Add(destination, resultDestinations); return(resultDestinations); }
public async Task <List <Picture> > GetBingPicture() { if (!Barrel.Current.IsExpired(ConfigApi.DestinationKey)) { return(Barrel.Current.Get <List <Picture> >(ConfigApi.DestinationKey)); } string[] searchDestinations = new string[] { "Seattle", "Maui", "Nueva York", "Antarctica", "República Dominicana" }; var clientImage = new ImageSearchClient(new ApiKeyServiceClientCredentials(ConfigApi.BingImageSearch)); List <Picture> resultDestination = new List <Picture>(); try { foreach (var item in searchDestinations) { var result = await clientImage.Images.SearchAsync(item, color : "blue", minWidth : 500, minHeight : 500, imageType : "Photo", license : "Public", count : 5, maxHeight : 1200, maxWidth : 1200); int randomIndex = random.Next(result.Value.Count); resultDestination.Add(new Picture { Title = item, Image = result.Value[randomIndex].ContentUrl, Uri = result.Value[randomIndex].HostPageUrl }); } Barrel.Current.Add(ConfigApi.DestinationKey, data: resultDestination, TimeSpan.FromDays(60)); return(resultDestination); } catch (Exception) { return(resultDestination); } }
public async Task ImageSearch(string subscriptionKey, string query) { var client = new ImageSearchClient(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(subscriptionKey)); try { var imageResults = client.Images.SearchAsync(query).Result; if (imageResults != null) { var activity = MessageFactory.Attachment(new Attachment[] { new Attachment { ContentUrl = imageResults.Value[0].ContentUrl, ContentType = "image/png" }, new Attachment { ContentUrl = imageResults.Value[1].ContentUrl, ContentType = "image/png" }, new Attachment { ContentUrl = imageResults.Value[2].ContentUrl, ContentType = "image/png" } }); await context.SendActivityAsync("Searching for images related to " + query); await context.SendActivityAsync(activity); } } catch (Exception ex) { await context.SendActivityAsync("Could not retrieve image results due to:" + ex.Message); } }
protected BingImageSearchService() { const string subscriptionKey = "70c508d2c10147f79d9d260042ade225"; var credentials = new ApiKeyServiceClientCredentials(subscriptionKey); _client = new ImageSearchClient(credentials); }
public void ImageSearch() { using (MockContext context = MockContext.Start(this.GetType())) { HttpMockServer.Initialize(this.GetType(), "ImageSearch"); IImageSearchClient client = new ImageSearchClient(new ApiKeyServiceClientCredentials(SubscriptionKey), HttpMockServer.CreateInstance()); var resp = client.Images.SearchAsync(query: Query).Result; Assert.NotNull(resp); Assert.NotNull(resp.WebSearchUrl); Assert.NotNull(resp.Value); Assert.True(resp.Value.Count > 0); var image = resp.Value[0]; Assert.NotNull(image.WebSearchUrl); Assert.NotNull(image.ThumbnailUrl); Assert.NotNull(resp.QueryExpansions); Assert.True(resp.QueryExpansions.Count > 0); var query = resp.QueryExpansions[0]; Assert.NotNull(query.Text); Assert.NotNull(query.SearchLink); } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, [ServiceBus("images-to-classify", Connection = "ProcessQueue", EntityType = EntityType.Queue)] IAsyncCollector <string> outputMessages) { string emotion = req.Query["emotion"].FirstOrDefault() ?? "happy"; string criteria = req.Query["search"].FirstOrDefault() ?? "random people with different emotions"; log.LogInformation($"Finding people with emotion: {emotion}"); // Get images from a Bing search var key = System.Environment.GetEnvironmentVariable("BingSearchKey"); var search = new ImageSearchClient(new ApiKeyServiceClientCredentials(key)); var results = await search.Images.SearchAsync(criteria, safeSearch : "Strict", count : 100); //var connection = Environment.GetEnvironmentVariable("ProcessQueue"); //var q = new QueueClient(connection, "images-to-classify"); foreach (var result in results.Value) { var data = $"{{ 'emotion': '{emotion}', 'imageUrl': '{result.ContentUrl}', 'fileName': '{result.ImageId + '.' + result.EncodingFormat}' }}"; await outputMessages.AddAsync(data); } return(new OkResult()); }
public void ImageDetail() { using (MockContext context = MockContext.Start(this.GetType())) { HttpMockServer.Initialize(this.GetType(), "ImageDetail"); IImageSearchClient client = new ImageSearchClient(new ApiKeyServiceClientCredentials(SubscriptionKey), HttpMockServer.CreateInstance()); var resp = client.Images.DetailsAsync(query: Query, insightsToken: ImageInsightsToken, modules: Modules).Result; Assert.NotNull(resp); Assert.NotNull(resp.BestRepresentativeQuery); Assert.NotNull(resp.ImageCaption); Assert.NotNull(resp.PagesIncluding); Assert.True(resp.PagesIncluding.Value.Count > 0); var pageIncluding = resp.PagesIncluding.Value[0]; Assert.NotNull(pageIncluding.HostPageUrl); Assert.NotNull(pageIncluding.WebSearchUrl); Assert.NotNull(resp.RelatedSearches); Assert.True(resp.RelatedSearches.Value.Count > 0); var relatedSearch = resp.RelatedSearches.Value[0]; Assert.NotNull(relatedSearch.Text); Assert.NotNull(relatedSearch.WebSearchUrl); Assert.NotNull(resp.VisuallySimilarImages); Assert.True(resp.VisuallySimilarImages.Value.Count > 0); var visuallySimilarImage = resp.VisuallySimilarImages.Value[0]; Assert.NotNull(visuallySimilarImage.WebSearchUrl); Assert.NotNull(visuallySimilarImage.ImageInsightsToken); } }
public void ImageTrending() { using (MockContext context = MockContext.Start(this.GetType())) { HttpMockServer.Initialize(this.GetType(), "ImageTrending"); IImageSearchClient client = new ImageSearchClient(new ApiKeyServiceClientCredentials(SubscriptionKey), HttpMockServer.CreateInstance()); var resp = client.Images.TrendingAsync().Result; Assert.NotNull(resp); Assert.NotNull(resp.Categories); Assert.True(resp.Categories.Count > 0); var category = resp.Categories[0]; Assert.NotNull(category.Title); Assert.NotNull(category.Tiles); Assert.True(category.Tiles.Count > 0); var categoryTile = category.Tiles[0]; Assert.NotNull(categoryTile.Image); Assert.NotNull(categoryTile.Query); } }
public IList <ImageObject> GetImagesFromApi(string searchTerm) { string subscriptionKey = "63a26ea020de4f7f833f549e8ae13b6f"; Images imageResults = null; try { var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey)); imageResults = client.Images.SearchAsync(query: searchTerm).Result; } catch { Console.WriteLine("NO INTERNET OR AUTH ERROR"); } if (imageResults == null) { return(null); } else { return(imageResults.Value); } }
public Images SearchImages(string searchTerm) { string subscriptionKey = "014247d4c10341f8b40a519e67641e32"; var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey)); Images imageResult = client.Images.SearchAsync(query: searchTerm).Result; return(imageResult); }
public BingImageSearch() { string subscriptionKey = "4f489680f20742cc9839ac4cdb9e8f0b"; //stores the image results returned by Bing // the image search term to be used in the query client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey)); }
// Add SearchBing public async Task SearchBing(ITurnContext context, string searchText) { // Step 1: Call the Bing Image Search API //IMPORTANT: replace this variable with your Cognitive Services subscription key. string subscriptionKey = "YourBingKey"; //initialize the client var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey)); //images to be returned by the Bing Image Search API Images imageResults = null; try { // Call the API and store the results imageResults = client.Images.SearchAsync(query: searchText).Result; //search query } catch (Exception ex) { // If there's an exception, return the error in the chat window await context.SendActivityAsync("Encountered exception. " + ex.Message); } // Step 2: Process the results and send to the user // If the API returns images if (imageResults != null) { // Parse out the first five images from ImageResults // Add the content URL to a simple message attachment var activity = MessageFactory.Attachment(new Attachment[] { new Attachment { ContentUrl = imageResults.Value[0].ContentUrl, ContentType = "image/png" }, new Attachment { ContentUrl = imageResults.Value[1].ContentUrl, ContentType = "image/png" }, new Attachment { ContentUrl = imageResults.Value[2].ContentUrl, ContentType = "image/png" }, new Attachment { ContentUrl = imageResults.Value[3].ContentUrl, ContentType = "image/png" }, new Attachment { ContentUrl = imageResults.Value[4].ContentUrl, ContentType = "image/png" } }); // Send the activity to the user. await SearchResponses.ReplyWithBingResults(context, searchText); await context.SendActivityAsync(activity); } else // If the API doesn't return any images { await SearchResponses.ReplyWithNoResults(context, searchText); } }
public IActionResult IndexGet(ImageSearchParameters imageSearchParameters) { if (!string.IsNullOrEmpty(imageSearchParameters.Query)) { ImageSearchClient client = new ImageSearchClient(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(_config["Keys:BingSearch"])); Images imageResults = client.Images.SearchAsync(query: imageSearchParameters.Query, offset: imageSearchParameters.Offset, count: imageSearchParameters.Count).Result; TempData.Put("Images", imageResults); } return(View("~/Views/Projects/BingSearch/Index.cshtml", imageSearchParameters)); }
/// <summary> /// Perform a bing image search and return the top image. /// </summary> /// <param name="celebrity">The celebrity to search for.</param> /// <returns>The description of the celebrity.</returns> private async Task <Image> SearchForImage(string searchText) { var client = new ImageSearchClient(SEARCH_KEY); client.Url = SEARCH_API; // force use of v7 api var request = new ImageSearchRequest() { Query = searchText }; var response = await client.GetImagesAsync(request); return(response.Images.FirstOrDefault()); }
public async Task CreateImageObjectsFromSearch(MessageObject <ShowObject> message, ILogger log, int count = 10) { //Leverage the Cognitive Services Bing Search API and log out the action IImageSearchClient client = new ImageSearchClient(new ImageApiKeyServiceClientCredentials(Environment.GetEnvironmentVariable("bingSearchSubscriptionKey"))); log.LogInformation($"[Request Correlation ID: {message.Headers.RequestCorrelationId}] :: Searching for associated images"); Images imageResults = client.Images.SearchAsync(query: $"{message.Body.ShowName} (Musical)", count: count).Result; //Initialise a temporaryObject and loop through the results //For each result, create a new NewsObject which has a condensed set //of properties, for storage in CosmosDB in line with the show data model //Once looped through send an OK Result //TODO: There is definitely a better way of doing this, but got a rough working approach out MessageObject <ImageObject> _object = new MessageObject <ImageObject>() { Body = null, Headers = new MessageHeaders() { RequestCorrelationId = message.Headers.RequestCorrelationId, RequestCreatedAt = DateTime.Now } }; foreach (Microsoft.Azure.CognitiveServices.Search.ImageSearch.Models.ImageObject image in imageResults.Value) { try { _object.Body = new Models.ImageObject() { Id = Guid.NewGuid().ToString(), ContentUrl = image.ContentUrl, HostPageUrl = image.HostPageUrl, ImageId = image.ImageId, Name = image.Name, CreatedAt = DateTime.Now, Doctype = DocTypes.Image, Partition = message.Body.Partition }; await _dataLayer.CreateImageAsync(_object); log.LogInformation($"[Request Correlation ID: {message.Headers.RequestCorrelationId}] :: Image Creation Success :: Image ID: {_object.Body.ImageId} "); } catch (Exception ex) { log.LogInformation($"[Request Correlation ID: {message.Headers.RequestCorrelationId}] :: Image Creation Fail :: :: Image ID: {_object.Body.ImageId} - {ex.Message}"); } } }
public void GetImagesTest() { var request = new ImageSearchRequest(); request.Query = "cats"; request.Count = 10; request.Offset = 0; request.Market = "en-US"; request.SafeSearch = SafeSearch.Moderate; var client = new ImageSearchClient(this.apiKey); var response = client.GetImages(request); Assert.IsTrue(response.Images.Count > 0); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { // check request log.LogInformation("Starting image search function"); string searchTerm = req.Query["search"]; if (string.IsNullOrEmpty(searchTerm)) { return(new BadRequestObjectResult("Please pass a search on the query string")); } log.LogInformation($"Search term is: {searchTerm}"); // get cognitive services api key from config and create image search client var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); string apiKey = config["CognitiveServicesKey"]; if (string.IsNullOrEmpty(apiKey)) { return(new InternalServerErrorResult()); } var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(apiKey)); // perform image search and return result var searchResult = await client.Images.SearchAsync(searchTerm); var images = searchResult.Value.Select(searchItem => new ImageSearchItem { FullImageUrl = searchItem.ContentUrl, PreviewImageUrl = searchItem.ThumbnailUrl }).ToList(); return(new ContentResult() { Content = JsonConvert.SerializeObject(new ImageSearchResult { Images = images, SearchTerms = searchTerm }), ContentType = "application/json", StatusCode = (int)HttpStatusCode.OK }); }
//return Images fetched through Bing Image Search API for a particular query string public static Images ImageSearch(string queryString) { string subscriptionKey = "5bca1b71485849c99c362c4c7299102e"; Images imageResult = null; // initializing search client. var searchClient = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey)); try { imageResult = searchClient.Images.SearchAsync(query: queryString).Result; return(imageResult); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
public static IServiceCollection AddImageSearchClient(this IServiceCollection services, IConfiguration config) { ConfigureImageSearchClient(services, config); services.AddTransient <IImageSearchClient>(serviceProvider => { ImageSearchClientSettings settings = serviceProvider.GetRequiredService <ImageSearchClientSettings>(); ImageSearchClient searchClient = new ImageSearchClient( new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(settings.SubscriptionKey), System.Array.Empty <System.Net.Http.DelegatingHandler>()) { Endpoint = settings.Endpoint }; return(searchClient); }); return(services); }
private async Task <List <string> > Search(string searchTerm) { var cacheKey = $"search-{searchTerm}"; if (_cache.TryGetValue(cacheKey, out List <string> cacheEntry)) { return(cacheEntry); } var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(_config.FaceApi)) { Endpoint = _config.Endpoint }; HttpOperationResponse <Images> results; try { _logger.LogInformation($"Image search for '{searchTerm}'."); results = await client.Images.SearchWithHttpMessagesAsync( searchTerm, safeSearch : "Moderate", countryCode : "no-no" ); } catch (Exception e) { _logger.LogCritical(e, "Image search failed."); return(null); } var searchResults = results?.Body?.Value; if (searchResults != null) { cacheEntry = searchResults.Take(10).Select(x => x.ContentUrl).ToList(); } _cache.Set(cacheKey, cacheEntry, DateTime.Now.AddDays(1)); return(cacheEntry); }
// Searches for results on query (Canadian Rockies) and gets an ImageInsightsToken. // Also prints first image insights token, thumbnail url, and image content url. private static String ImageResults(String subKey) { String insightTok = "None"; try { var client = new ImageSearchClient(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(subKey)); // var imageResults = client.Images.SearchAsync(query: "canadian rockies").Result; Console.WriteLine("Search images for query \"canadian rockies\""); if (imageResults == null) { Console.WriteLine("No image result data."); } else { // Image results if (imageResults.Value.Count > 0) { var firstImageResult = imageResults.Value.First(); Console.WriteLine($"\r\nImage result count: {imageResults.Value.Count}"); insightTok = firstImageResult.ImageInsightsToken; Console.WriteLine($"First image insights token: {firstImageResult.ImageInsightsToken}"); Console.WriteLine($"First image thumbnail url: {firstImageResult.ThumbnailUrl}"); Console.WriteLine($"First image content url: {firstImageResult.ContentUrl}"); } else { insightTok = "None found"; Console.WriteLine("Couldn't find image results!"); } } } catch (Exception ex) { Console.WriteLine("\r\nEncountered exception. " + ex.Message); } return(insightTok); }
public static Images ImageSearch(string queryString) { string subscriptionKey = ConfigurationManager.AppSettings["BingImageSearchApiSubscriptionKey"]; Images imageResult = null; var searchClient = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey)); try { int count = 60; int offset = count; imageResult = searchClient.Images.SearchAsync(query: queryString, count: count, offset: offset).Result; return(imageResult); } catch (Exception e) { Console.WriteLine(e.Message); return(null); } }
static void Main(string[] args) { //IMPORTANT: replace this variable with your Cognitive Services subscription key. string subscriptionKey = "ENTER YOUR KEY HERE"; // the image search term used in the query string searchTerm = "canadian rockies"; //initialize the client //NOTE: If you're using version 1.2.0 or below for the Bing Image Search client library, // use ImageSearchAPI() instead of ImageSearchClient() to initialize your search client. var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey)); Console.WriteLine("This application will send an HTTP request to the Bing Image Search API for {0} and print the response.", searchTerm); //images to be returned by the Bing Image Search API Images imageResults = null; //try to send the request, and get the results. Console.WriteLine("Search results for the image query: {0}", searchTerm); try { imageResults = client.Images.SearchAsync(query: searchTerm).Result; //search query } catch (Exception ex) { Console.WriteLine("Encountered exception. " + ex.Message); } if (imageResults != null) { //display the details for the first image result. After running the application, //you can copy the resulting URLs from the console into your browser to view the image. var firstImageResult = imageResults.Value.First(); Console.WriteLine($"\nTotal number of returned images: {imageResults.Value.Count}\n"); Console.WriteLine($"Copy the following URLs to view these images on your browser.\n"); Console.WriteLine($"URL to the first image:\n\n {firstImageResult.ContentUrl}\n"); Console.WriteLine($"Thumbnail URL for the first image:\n\n {firstImageResult.ThumbnailUrl}"); Console.Write("\nPress Enter to exit "); Console.ReadKey(); } }
IEnumerator setup() { var imageSearchClient = new ImageSearchClient(); yield return(StartCoroutine(imageSearchClient.Search(SearchWord, TheNumberOfPhotos))); var httpClient = new HttpClient(); yield return(StartCoroutine(httpClient.GetTextures(imageSearchClient.ImageUriList))); Debug.Log("ImageDownload OK"); var textures = httpClient.ResponsedTextures; for (int i = 0; i < textures.Count; ++i) { var frame = Instantiate(PhotoFramePrefab); frame.transform.parent = gameObject.transform; frame.transform.rotation = new Quaternion(0, 0, 0, 0); frame.GetComponent <Renderer>().material.mainTexture = textures[i]; frame.transform.position = calcPhotFramePosition(i); } }
public async Task <List <Destination> > GetDestinations() { var searchDestinations = new[] { "Seattle", "Maui", "Amsterdam", "Antarctica", "Buenos Aires" }; try { var client = new ImageSearchClient(new Microsoft.Azure.CognitiveServices.Search.ImageSearch.ApiKeyServiceClientCredentials(ApiKeys.BingImageSearch)); var resultDestinations = new List <Destination>(); foreach (var destination in searchDestinations) { var result = await client.Images.SearchAsync(destination, color : "blue", minWidth : 500, minHeight : 500, imageType : "Photo", license : "Public", count : 5, maxHeight : 1200, maxWidth : 1200); var randomIdx = _randomResultIndex.Next(result.Value.Count); resultDestinations.Add(new Destination { Title = destination, ImageUrl = result.Value[randomIdx].ContentUrl, MoreInfoUrl = result.Value[randomIdx].HostPageUrl, News = await GetNews(destination) }); } return(resultDestinations); } catch { return(new List <Destination> { new Destination { Title = "Something went wrong :( Here is a cat instead!", ImageUrl = "https://cataas.com/cat", MoreInfoUrl = "https://cataas.com/" } }); } }
//move from text groupBox to image groupBox and also load in all bold text and title to load images private void Button_next2_Click(object sender, EventArgs e) { string key = "35e097947bfd47c690722ee36f91b353"; Images imageResults = null; string bold_words = bolded_words(); string searchTerm = this.textBox_title.Text + " " + bold_words; Console.WriteLine(searchTerm); var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(key)); imageResults = client.Images.SearchAsync(query: searchTerm).Result; if (imageResults == null) { MessageBox.Show("Failed to search for images with given title and bold text"); } else { ImageResult_url = new string[9]; for (int i = 0; i < 9; i++) { ImageResult_url[i] = imageResults.Value[i].ThumbnailUrl; } pictureBox1.Load(ImageResult_url[0]); pictureBox2.Load(ImageResult_url[1]); pictureBox3.Load(ImageResult_url[2]); pictureBox4.Load(ImageResult_url[3]); pictureBox5.Load(ImageResult_url[4]); pictureBox6.Load(ImageResult_url[5]); pictureBox7.Load(ImageResult_url[6]); pictureBox8.Load(ImageResult_url[7]); pictureBox9.Load(ImageResult_url[8]); this.groupBox_welcome.Hide(); this.groupBox_text.Hide(); this.groupBox_images.Show(); this.groupBox_output.Hide(); } }
public async Task <List <Destination> > GetDestinations() { var searchDestinations = new[] { "Switzerland", "Zurich", "Alps", "Berne" }; try { var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(ApiKeys.BingImageSearch)); var resultDestinations = new List <Destination>(); foreach (var destination in searchDestinations) { var result = await client.Images.SearchAsync(destination, color : "blue", minWidth : 500, minHeight : 500, imageType : "Photo", license : "Public", count : 5, maxHeight : 1200, maxWidth : 1200); var randomIdx = _randomResultIndex.Next(result.Value.Count); resultDestinations.Add(new Destination { Title = destination, ImageUrl = result.Value[randomIdx].ContentUrl, MoreInfoUrl = result.Value[randomIdx].HostPageUrl }); } return(resultDestinations); } catch { return(new List <Destination> { new Destination { Title = "Something went wrong :( Here is a cat instead!", ImageUrl = "https://cataas.com/cat", MoreInfoUrl = "https://cataas.com/" } }); } }