Posted 12 years ago
·
Author
The following code will basically let you search google's new API for image searching without ever loading the google page, just note this is still beta and may not compile outside of .net 4.0 sorry
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace Toyz_Portfoilo.sBin
{
public class SBIHelper
{
private static HttpWebResponse _response;
public static string SearchByImage(string url)
{
var request = WebRequest.Create(String.Format("http://www.google.com/searchbyimage?hl=en&site=search&image_url={0}", url)) as HttpWebRequest;
var sb = new StringBuilder();
var buf = new byte[8192];
if (request != null)
{
request.Method = "GET";
request.ProtocolVersion = HttpVersion.Version11;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0";
_response = request.GetResponse() as HttpWebResponse;
}
if (_response != null)
{
var stream = _response.GetResponseStream();
var count = 0;
do
{
if (stream != null) count = stream.Read(buf, 0, buf.Length);
if (count == 0) continue;
var tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
} while (count > 0);
}
string re1 = "(;)";
string re2 = "(q)";
string re3 = "(=)";
string re4 = "((?:[a-z][a-z]+))";
string re5 = ".*?";
string re6 = "(&)";
var r = new Regex(re1 + re2 + re3 + re4 + re5 + re6, RegexOptions.IgnoreCase | RegexOptions.Singleline);
var match = r.Match(sb.ToString());
var imageName = match.Success ? match.ToString().Remove(0, 3).TrimEnd('&').Replace("%20", " ") : null;
return imageName;
}
}
}