Using Google Image Search, Picking first 9 image results using c#.net

不羁的心 提交于 2021-02-17 07:16:47

问题


In Short, I need to figure out how to use Google API's to do a Google Image Search Based off of text in a RichBox named "Title" and ONLY bold words in another RichBox named "Body". The idea of this is to create an Image Suggestion page that will be used to help produce PowerPoint slides.

Here is the code I've Tried to Get a Google Image Search going.

For Start we have two RichBoxes named "Title" & "Body".

Whatever the user types in the "Title" box, it gets stored in a List of "Search Term" Strings

 private void TitleTextBox2_TextChanged(object sender, EventArgs e)
        {
            _searchTerms.Add(textBox2.Text.ToString());
        }

We use the same Method for the "Body" Rich box with an added if Statement check to see if the BOLD Boolean is true or false, If Bold is true, then we had the current text change into the list of "Search Terms" strings.

 private void BodyTextBox_TextChanged_1(object sender, EventArgs e)
        {
            if (ControllerSlide.bold == true)
            {
                this.richTextBox1.Select();
                this.richTextBox1.SelectionFont = new Font(richTextBox1.Font, 
                System.Drawing.FontStyle.Bold);
                _searchTerms.Add(richTextBox1.Text.ToString());
            }
            else
            {
                this.richTextBox1.Select();
                this.richTextBox1.SelectionFont = new Font(richTextBox1.Font, 
                System.Drawing.FontStyle.Regular);
            }

        }

So now that we have a list of Search Terms Here comes the tricky part that I am Stuck at. I have a button called "Generate" which will call on the Functions to Implement the Search Term List, and Use it to generate 9 search images.

We have a function called GetHTMLCode()

private string GetHtmlCode()
        {
            var rnd = new Random();

        
            int topic = rnd.Next(0, _searchTerms.Count - 1);

            string url = "https://www.google.com/search?q=" + _searchTerms[topic] + "&tbm=isch";
            string data = "";

            var request = (HttpWebRequest)WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();

            using (Stream dataStream = response.GetResponseStream())
            {
                if (dataStream == null)
                    return "";
                using (var sr = new StreamReader(dataStream))
                {
                    data = sr.ReadToEnd();
                }
            }
            return data;
        }

This is suppose to generate a random index count to be chosen in the list of _searchTerms and returns the data back.

Next we have the function GetURLs

 private List<string> GetUrls(string html)
        {
            
            var urls = new List<string>();

            string search = @",""ou"":""(.*?)"",";
            MatchCollection matches = Regex.Matches(html, search);

            foreach (Match match in matches)
            {
                urls.Add(match.Groups[1].Value);
            }

            return urls;
        }

Next we have the GetImage() Function

 private byte[] GetImage(string url)
        {


            var request = (HttpWebRequest)WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();

            using (Stream dataStream = response.GetResponseStream())
            {
                if (dataStream == null)
                    return null;
                using (var sr = new BinaryReader(dataStream))
                {
                    byte[] bytes = sr.ReadBytes(100000000);

                    return bytes;
                }
            }

            return null;
        }

this grabs the images and stores them in Byte data

finally to tie them together is the "GenerateButtonClick" Function

 private void GenerateButton_Click(object sender, EventArgs e)
        {
            var client = new GwebSearchClient("https://www.google.com/search?q=" 
            + _searchTerms + "&tbm=isch");
            var results = client.Search("google", 9);
            foreach (var webResult in results)
            {
                Console.WriteLine("{0}, {1}, {2}", webResult.Title, 
                webResult.Url, webResult.Content);
                listView1.Items.Add(webResult.ToString());
            }

            if(_searchTerms.Count <= 0)
            {
                System.Windows.MessageBox.Show("Please add Title or Body text" ); 
 return;
            }
            else
            {
                string html = GetHtmlCode();
                List<string> urls = GetUrls(html);
                var rnd = new Random();

                if(urls.Count <= 0)
                {
                    System.Windows.MessageBox.Show("URLs Count is zero" + 
                    urls.Count.ToString()); return;
                }
                else
                {
                    int randomUrl = rnd.Next(0, urls.Count);

                    string luckyUrl = urls[0];

                    byte[] image = GetImage(luckyUrl);

                    using (var ms = new MemoryStream(image))
                    {
                        pictureBox1.Image = Image.FromStream(ms);
                    }

                }
              
            } 
            
            imageResultsPage = new ImageResultsPage();
            imageResultsPage.Show();

        }

Right now my problem is that my url.Count is always equal to 0. And I can't Figure out the issue.

Also, if there is a better way to Generate a Google Image search and have the first 9 images displayed on 9 picture boxes in a form, I am open to changing any code or completely changing the structure.

I am using visual Studios 2019 c#.net

PS. I am fairly new to all of this. Thanks for any help!

来源:https://stackoverflow.com/questions/65781129/using-google-image-search-picking-first-9-image-results-using-c-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!