通常、Googleを使用して都市を検索した後、右側に画像と地図が表示されたWikipediaページの一部があります。この画像にアクセスする方法を教えてもらえますか?ダウンロード方法を知っておく必要があります。
実際、メイン画像(右側の地図画像に付属)がウィキペディアからのものであることはめったにないため、ウィキペディアAPIを使用して取得することはできません。実際のメイン画像にアクセスしたい場合は、これを使用できます。
private static void GetGoogleImage(string word)
{
// make an HTTP Get request
var request = (HttpWebRequest)WebRequest.Create("https://www.google.com.pg/search?q=" + word);
request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36";
using (var webResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
// get all images with base64 string
var matches = Regex.Matches(reader.ReadToEnd(), @"'data:image/jpeg;base64,([^,']*)'");
if (matches.Count > 0)
{
// get the image with the max height
var bytes = matches.Cast<Match>()
.Select(x => Convert.FromBase64String(x.Groups[1].Value.Replace("\\75", "=").Replace("\\075", "=")))
.OrderBy(x => Image.FromStream(new MemoryStream(x, false)).Height).Last();
// save the image as 'image.jpg'
using (var imageFile = new FileStream("image.jpg", FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
}
}
}
}
これは私にとってはうまくいき、常に実際のメイン画像を返します(存在する場合)。例えば、GetGoogleImage("New York")
私に与えてデータを:画像/ JPEGを、base64で、/ 9J / 4AAQSkZJRg ...。
応答としてすべてのbase64文字列画像からメインの高さが最大であるという事実を使用します。したがって、高さで並べ替えて最後の画像を選択するだけで済みます。必要に応じて、ここで最小画像高さも確認できます。への置き換え\075
に=
は、base64のパディングが必要です。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加