从Google选择并下载随机图片 [英] Select and Download random image from Google

查看:62
本文介绍了从Google选择并下载随机图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有示例可以从Google搜索和下载随机图片?使用随机搜索字符串?

Is there any example how I can search and download a random image from google? Using a random search string?

我想将此图像用作隐写图像,并且希望它是随机的.

I want to use this image as steganography image and I want it to be a random one.

我在Visual Studio 2012中使用C#.

I am using C# with Visual Studio 2012.

推荐答案

您可能不希望使用随机搜索字符串.您可能需要随机主题.这里有一些代码可以帮助您.首先,创建主题列表:

You probably don't want a random search string. You probably want random topics. Here is some code to help you out. First, create a list of topics:

private readonly List<string> _topics = new List<string> {"dog", "car", "truck", "cat", "florida"};

当然,您可以随意更改,添加和删除任意数量的主题.接下来,我们将创建一个函数来从Google图片搜索中检索HTML代码,并随机选择我们要搜索的主题之一:

Of course, you are free to change, add and remove as many topics as you wish. Next, we will create a function to retrieve the HTML code from a Google image search, randomly selecting one of our topics to search from:

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

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

    string url = "https://www.google.com/search?q=" + _topics[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;
}

有了HTML代码后,我们需要解析出images_table表下方的img标签,并将图像的URL存储在列表中:

Once we have the HTML code, we need to parse out the img tags located underneath the images_table table and store the URL's of the images in a list:

private List<string> GetUrls(string html)
{
    var urls = new List<string>();
    int ndx = html.IndexOf("class=\"images_table\"", StringComparison.Ordinal);
    ndx = html.IndexOf("<img", ndx, StringComparison.Ordinal);

    while (ndx >= 0)
    {
        ndx = html.IndexOf("src=\"", ndx, StringComparison.Ordinal);
        ndx = ndx + 5;
        int ndx2 = html.IndexOf("\"", ndx, StringComparison.Ordinal);
        string url = html.Substring(ndx, ndx2 - ndx);
        urls.Add(url);
        ndx = html.IndexOf("<img", ndx, StringComparison.Ordinal);
    }
    return urls;
}

我们需要的最后一个功能是获取一个URL,并将其下载图像字节到字节数组中:

Our last function we need is to take an URL and have it download the image bytes into a byte array:

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(100000);

            return bytes;
        }
    }

    return null;
}

最后,我们只需要将它们绑在一起即可

Finally, we just need to tie it all together:

string html = GetHtmlCode();
List<string> urls = GetUrls(html);
var rnd = new Random();

int randomUrl = rnd.Next(0, urls.Count - 1);

string luckyUrl = urls[randomUrl];

byte[] image = GetImage(luckyUrl);
using (var ms = new MemoryStream(image))
{
    pictureBox1.Image = Image.FromStream(ms);
}


更新

关于这个答案,我收到了一些要求,要求我对其进行修改,以便它加载实际的全尺寸图像而不是缩略图.我已经修改了原始代码,因此现在可以加载完整尺寸的图像,而不是缩略图.

I've gotten a few requests about this answer asking that I modify it so it loads the actual full size image rather than the thumbnail. I have modified my original code so that it loads the full size images now instead of the thumbnails.

首先,像以前一样,创建主题列表:

First, like before, create a list of topics:

private readonly List<string> _topics = new List<string> { "dog", "car", "truck", "cat", "florida" };

当然,您可以随意更改,添加和删除任意数量的主题.接下来,我们将创建一个函数来从Google图片搜索中检索HTML代码,并随机选择要搜索的主题之一. GetHtmlCode()在缩略图版本中与GetHtmlCode()有所不同,我们必须在请求中添加AcceptUserAgent,否则Google不会为我们提供完整尺寸的图像网址:

Of course you are free to change, add and remove as many topics as you wish. Next we will create a function to retrieve the HTML code from a Google image search, randomly selecting one of our topics to search from. GetHtmlCode() here is different from the GetHtmlCode() in the thumbnail version in that we must add an Accept and a UserAgent to the request or else Google won't give us the full size image URLs:

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

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

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

    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Accept = "text/html, application/xhtml+xml, */*";
    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";

    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;
}

GetUrls()方法也被重写,因为我们现在返回的HTML代码与我们在缩略图"版本中返回的HTML代码不同.它仍然从HTML代码中解析URL:

The GetUrls() method was also rewritten because the HTML code we get back now is different from the HTML code we got back in our "thumbnail" version. It still parses out the URLs from the HTML code:

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

    int ndx = html.IndexOf("\"ou\"", StringComparison.Ordinal);

    while (ndx >= 0)
    {
        ndx = html.IndexOf("\"", ndx + 4, StringComparison.Ordinal);
        ndx++;
        int ndx2 = html.IndexOf("\"", ndx, StringComparison.Ordinal);
        string url = html.Substring(ndx, ndx2 - ndx);
        urls.Add(url);
        ndx = html.IndexOf("\"ou\"", ndx2, StringComparison.Ordinal);
    }
    return urls;
}

我们需要的最后一个功能是获取一个URL,并将其下载图像字节到字节数组中.此功能只有一个小变化,与缩略图"版本不同.我们必须更改ReadBytes()中的数字,因为我们的图像现在会更大:

Our last function we need is to take an URL and have it download the image bytes into a byte array. There is only one minor change in this function that's different from the "thumbnail" version. We had to change the number in ReadBytes() since our images will be larger now:

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;
}

最后,我们只需要将它们绑在一起,就像以前一样:

Finally, we just need to tie it all together, like before:

string html = GetHtmlCode();
List<string> urls = GetUrls(html);
var rnd = new Random();

int randomUrl = rnd.Next(0, urls.Count - 1);

string luckyUrl = urls[randomUrl];

byte[] image = GetImage(luckyUrl);
using (var ms = new MemoryStream(image))
{
    pictureBox1.Image = Image.FromStream(ms);
}

这篇关于从Google选择并下载随机图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆