[C#] 透過圖片搜尋取得關鍵字

2013-05-22

Google 很強大,現在可以做到用圖片搜尋圖片..

2013-05-21_192225

 

一直很想寫一個功能,看看有沒有辦法,隨便給一個圖片網址,讓Google來告訴我這關鍵字是啥..

像這張照片,我根本不知道這女生是誰..

f64fb0a1943d436fb6d24bf57bd2c422

接下來我們看看如何去處理..

首先此圖片網址為 :https://lh5.googleusercontent.com/-CHktInzJEZc/UZtf2re3fFI/AAAAAAAAE8U/mJvjLrMFziQ/w510-h339-no/935108_443537695740527_1574849830_n.jpg

 

/// <summary>
/// 傳入圖片網址
/// </summary>
/// <param name="imagePath"></param>
/// <returns></returns>
private string GetKeyWordByImagePath(string imagePath)
{
    //透過直接透過傳遞參數取得資料
    var webRequest = WebRequest.Create(String.Format("http://www.google.com/searchbyimage?hl=zh-TW&site=search&image_url=" + imagePath)) as HttpWebRequest;
 
    webRequest.Method = "GET";
    webRequest.ProtocolVersion = HttpVersion.Version11;
    webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.220 Safari/535.1";
 
    var response = webRequest.GetResponse() as HttpWebResponse;
    var reader = new StreamReader( response.GetResponseStream());
 
    var str = reader.ReadToEnd();
  
    //Regex parsing.
    var regexId = new Regex(@"這個圖片最有可能的推測結果:(?<ID>.*?)搜尋結果",RegexOptions.IgnoreCase);
    MatchCollection mcId = regexId.Matches(str);
    if (mcId.Count != 0)
    {
        return Regex.Replace(mcId[0].Groups["ID"].Value, @"<[^>]*>", String.Empty).Replace("&nbsp;", "");
    }
    return ""; 
}


 


我們來看看結果..


 


2013-05-22_133417


這邊放幾張測試:


2013-05-22_132622 


2013-05-22_132905 


2013-05-22_133034 


程式下載:



文章參考:


一個做法一樣但是採樣法不一樣的lib : https://sbisharp.codeplex.com/


當麻許的超技八 2014 | Donma Hsu Design.