更新时间:2023-11-20 16:08:10
That code is updated here:
http://blogs.msdn.com/danielfe/archive/2004/07/26/197811.aspx
This is my code in Main.cs:
#region
Directivesusing
System;using
System.Collections.Generic;using
System.ComponentModel;using
System.Data;using
System.Drawing;using
System.Text;using
System.Windows.Forms;using
System.IO;using
System.Net;using
System.Diagnostics;using
Google_Image_Grabber;#endregion
namespace
Google_Image_Grabber{
public partial class Main : Form{
public Main(){
InitializeComponent();
}
internal Dictionary<string, Image> GoogleImages = new Dictionary<string, Image>();#region
Form Events private void button1_Click(object sender, EventArgs e){
ResetForm();
backgroundWorker1.RunWorkerAsync(textBox1.Text);
}
private void ResetForm(){
try{
listView1.Items.Clear();
imageList1.Images.Clear();
progressBar1.Value = 0;
progressBar1.Visible =
true;}
catch (System.Exception Ex){
LogError(Ex);
}
}
private void imageList_ItemActivate(object sender, EventArgs e){
ListView.SelectedListViewItemCollection Items = listView1.SelectedItems; string url = WebUtilities.ConvertToHighResGoogleUrl(@Items[0].Text); try{
using (Stream ImageStream = new WebClient().OpenRead(url)){
pictureBox1.Image =
Image.FromStream(ImageStream);}
}
catch{
//Use low res image if high res throws exceptionpictureBox1.Image = GoogleImages[Items[0].Text];
}
}
private void SetStretch_Click(object sender, EventArgs e){
Wallpaper.SetWallpaper(pictureBox1.Image, Wallpaper.Style.Stretched); MessageBox.Show("Wallpaper Changed");}
private void SetTile_Click(object sender, EventArgs e){
Wallpaper.SetWallpaper(pictureBox1.Image, Wallpaper.Style.Tiled); MessageBox.Show("Wallpaper Changed");}
private void SetCenter_Click(object sender, EventArgs e){
Wallpaper.SetWallpaper(pictureBox1.Image, Wallpaper.Style.Centered); MessageBox.Show("Wallpaper Changed");}
#endregion
#region
Background Worker Code private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){
int progress = 0; Dictionary<string, Image> UrlAndImage = new Dictionary<string, Image>(); //Parse Web Page for image Urls List<string> imgUrls = WebUtilities.GetImagesFromGoogle((string)e.Argument);backgroundWorker1.ReportProgress(progress++);
//Load images foreach (string url in imgUrls){
try{
Stream ImageStream = new WebClient().OpenRead(url); Image img = Image.FromStream(ImageStream);UrlAndImage.Add(url, img);
}
catch{ }
finally{
backgroundWorker1.ReportProgress(progress++);
}
}
//Send result back to Forme.Result = UrlAndImage;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){
progressBar1.Visible =
false;GoogleImages = (
Dictionary<string, Image>)e.Result; foreach (string key in GoogleImages.Keys){
imageList1.Images.Add(key, GoogleImages[key]);
listView1.Items.Add(key, key);
}
}
#endregion
#region
Utilities private void LogError(Exception Ex){
Debug.WriteLine(Ex.Message);}
#endregion
private void contextMenuStrip1_Click(object sender, EventArgs e){
Wallpaper.SetWallpaper(pictureBox1.Image, Wallpaper.Style.Stretched); MessageBox.Show("Wallpaper Changed");}
}
}
This is my code in WebUtilities.cs:
#region
Using directivesusing
System;using
System.Drawing;using
System.Collections.Generic;using
System.Text;using
System.Net;using
System.IO;using
System.Text.RegularExpressions;using
System.Diagnostics;#endregion
static
class WebUtilities{
#region
Google-Specific Methods /// <summary> /// Returns a list of URLs with low res images from Google /// </summary> /// <param name="search">text to search</param> /// <returns>Generic list of image URLs</returns> public static List<string> GetImagesFromGoogle(string search){
string googleUrl = "http://images.google.com/images?q=" + search; List<string> urlList = new List<string>(); string html = GetHtml(googleUrl); string regExPattern = @"< \s* img [^\>]* src \s* = \s* [\""\']? ( [^\""\'\s>]* )"; Regex r = new Regex(regExPattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); MatchCollection matches = r.Matches(html); foreach (Match m in matches){
//only return images from the search result (aka not Google's logo or ads) if (m.Groups[1].Value.ToString().IndexOf("/images?") != -1){
//Provide full path for image string imageUrl = @"http://images.google.com" + m.Groups[1].Value;urlList.Add(imageUrl);
}
}
return urlList;}
/// <summary> /// Given a low res URL from Google, returns the high[er] res URL for the image /// </summary> /// <param name="url">low res URL</param> /// <returns>high res URL</returns> public static string ConvertToHighResGoogleUrl(string url){
return @"http://" + @url.Substring(51); }#endregion
#region
Other Utility Methods /// <summary> /// Returns a stream of the contents of a URL /// </summary> /// <param name="url">A valid URL</param> /// <returns>URL contents</returns> public static Stream GetStreamFromUrl(string url){
return new WebClient().OpenRead(url); } /// <summary> /// Checks whether calling a URL will throw an exception /// </summary> /// <param name="url">URL to validate</param> /// <returns>true if no error was thrown</returns> public static bool ValidUrl(string url){
try{
using (System.IO.Stream s = new WebClient().OpenRead(url)){
return true;}
}
catch (System.Net.WebException ex){
Debug.WriteLine("Message: " + ex.Message); Debug.WriteLine("Status: " + ex.Status); return false;}
catch (System.Exception ex){
Debug.WriteLine("Message: " + ex.Message); return false;}
}
/// <summary> /// Retrieves a list of the image urls for a given web page /// </summary> /// <param name="url">a url</param> /// <returns>Generic list of image urls</returns> public static List<string> GetAllImagesFromUrl(string url){
List<string> urlList = new List<string>(); MatchCollection matches = GetImageMatches(url); foreach (Match m in matches){
urlList.Add(m.Groups[1].Value);
}
return urlList;}
/// <summary> /// Calls a url and retrieves the contents as a string /// </summary> /// <param name="url">url to retrieve</param> /// <returns>html string of url contents</returns> public static string GetHtml(string url){
using (StreamReader sr = new StreamReader(GetStreamFromUrl(url))){
return sr.ReadToEnd(); }}
#endregion
#region
Private Utility Methods private static MatchCollection GetImageMatches(string url){
string html = GetHtml(@url); string regExPattern = @"< \s* img [^\>]* src \s* = \s* [\""\']? ( [^\""\'\s>]* )"; Regex r = new Regex(regExPattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); MatchCollection matches = r.Matches(html); return matches;}
#endregion
}
This is my code in Wallpaper.cs:
#region
Using directivesusing
System;using
System.Collections.Generic;using
System.ComponentModel;using
System.Data;using
System.Drawing;using
System.Text;using
System.Windows.Forms;using
System.Runtime.InteropServices;using
System.IO;using
Microsoft.Win32;using
System.Net;#endregion
namespace
Google_Image_Grabber{
/// <summary> /// Wallpaper class used to set the Windows Wallpaper. /// </summary> public sealed class Wallpaper{
Wallpaper() { }
const int SPI_SETDESKWALLPAPER = 20; const int SPIF_UPDATEINIFILE = 0x01; const int SPIF_SENDWININICHANGE = 0x02;[
DllImport("user32.dll", CharSet = CharSet.Auto)] static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); public enum Style : int{
Tiled,
Centered,
Stretched
}
public static void SetWallpaper(Image img, Style style){
string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");img.Save(tempPath, System.Drawing.Imaging.
ImageFormat.Bmp); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true); if (style == Style.Stretched){
key.SetValue(
@"WallpaperStyle", 2.ToString());key.SetValue(
@"TileWallpaper", 0.ToString());}
else if (style == Style.Centered){
key.SetValue(
@"WallpaperStyle", 1.ToString());key.SetValue(
@"TileWallpaper", 0.ToString());}
else if (style == Style.Tiled){
key.SetValue(
@"WallpaperStyle", 1.ToString());key.SetValue(
@"TileWallpaper", 1.ToString());}
SystemParametersInfo(SPI_SETDESKWALLPAPER,
0,
tempPath,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
}
}
I realize that this is a lot of code to look over however I cannot get the images to show up in my ListView control but I see no error in the code and it debugs fine. I'm stumped.
That code is updated here:
http://blogs.msdn.com/danielfe/archive/2004/07/26/197811.aspx