Library code snippets

A shell for Google's image search

A program that searches on Google's Image Search.

/*
* by Mike H (GbaGuy) - http://k2pts.home.comcast.net/gbaguy/
*        vbnetprogramer@hotmail.com
*
* I don't care what you do with this. GPL.
*
* All the calls to GC.Collect() are probably unnecessary, but
* then again so are the dialog boxes that say "error: out of memory"...
*/
using System;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Collections;
using System.Drawing;
using System.Diagnostics;
class ImageSearch : Form {
    string searchstring = "http://images.google.com/images?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&q=";
    string alternatesearch = "http://images.google.com/images?q=SEARCH&svnum=10&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&filter=0";
    string resultpage = "";
    string startoftable = "table align=center border=0 cellpadding=5 cellspacing=0";
    string moreimglink = "http://images.google.com/images?q=SEARCH&svnum=10&hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&start=SET&sa=N";
    int seto20 = 0;
    ArrayList thumbs = new ArrayList();
    ArrayList googlethumbs = new ArrayList();
    ArrayList links = new ArrayList();
    ArrayList gtsizes = new ArrayList();
    ArrayList labels = new ArrayList();
   
    TextBox urlTB = new TextBox();
    string searchtext = "";
   
    MenuItem mnuOptions = new MenuItem("Options");
    MenuItem mnuNext = new MenuItem("Next");
    MenuItem mnuPrev = new MenuItem("Previous");
   
    private void next20(object s,EventArgs e) {
        seto20 += 20;
        try {
            search();
        } catch(Exception d) {
            d=d;
            seto20 -= 20;
            MessageBox.Show("No more pics.","Error");
        }
    }
   
    private void prev20(object s, EventArgs e) {
        if(seto20!=0) {
            seto20 -= 20;
        } else {
            MessageBox.Show("Can't go back.","Error");
            return;
        }
        try {
            search();
        } catch(Exception d) {
            d=d;
            MessageBox.Show("Can't go back.","Error");
        }
    }
   
    public ImageSearch() {
        urlTB.Dock = DockStyle.Top;
        urlTB.Multiline = true;
        urlTB.KeyDown += new KeyEventHandler(Key_Down);
        this.Controls.Add(urlTB);
        this.Text = "Image Search (Powered by Google)";
        this.WindowState = FormWindowState.Maximized;
        this.Menu = new MainMenu();
        this.Menu.MenuItems.Add(mnuOptions);
        mnuOptions.MenuItems.Add(mnuNext);
        mnuOptions.MenuItems.Add(mnuPrev);
        mnuNext.Click += new EventHandler(next20);
        mnuPrev.Click += new EventHandler(prev20);
        this.Show();
    }
       
    private void Key_Down(object s,KeyEventArgs e) {
        if(Keys.Enter==e.KeyCode) {
            e.Handled = true;
            seto20 = 0;
            searchtext = urlTB.Text;
            search();
            urlTB.Clear();
        }
    }
   
    private void search() {
        foreach(Label c in labels) {
            c.Image = null;
            c.Visible = false;
            c.Dispose();
        }
        Application.DoEvents();
        System.GC.Collect();
        Application.DoEvents();
        System.GC.Collect();
        googlethumbs = new ArrayList();
        thumbs = new ArrayList();
        links = new ArrayList();
        gtsizes = new ArrayList();
        WebClient WC = new WebClient();
        byte[] data = null;
        if(seto20!=0)
            data = WC.DownloadData(moreimglink.Replace("SEARCH",searchtext.Replace(" ","+")).Replace("SET",seto20.ToString()));
        else
            data = WC.DownloadData(searchstring + urlTB.Text.Replace(" ","+"));
        WC.Dispose();
        System.Text.ASCIIEncoding AE = new System.Text.ASCIIEncoding();
        resultpage = AE.GetString(data, 0, data.Length);
        resultpage = resultpage.Substring(resultpage.IndexOf(startoftable)+startoftable.Length);
        try {
            resultpage = resultpage.Substring(0,resultpage.IndexOf("Result Page: ));
        } catch(Exception e44) {
            e44=e44;
            WebClient Wc = new WebClient();
            byte[] daTa = Wc.DownloadData(alternatesearch.Replace("SEARCH",urlTB.Text.Replace(" ","+")));
            Wc.Dispose();
            System.Text.ASCIIEncoding Ae = new System.Text.ASCIIEncoding();
            resultpage = Ae.GetString(daTa, 0, daTa.Length);
            resultpage = resultpage.Substring(resultpage.IndexOf(startoftable)+startoftable.Length);
        }
        parse();
        //WriteToFile();
        resultpage = null;
        showIMGs();
    }
   
    private void showIMGs() {
        int x = 5;
        int y = 20;
        int largestY = 0;
        if(!Directory.Exists(@"C:\pics"))
            Directory.CreateDirectory(@"C:\pics");
        for(int i=0;i<thumbs.Count;i++) {
            Application.DoEvents();
            Label l = new Label();
            WebClient WC = new WebClient();
            try {
                byte[] im = WC.DownloadData((string)googlethumbs[i]);
                WC.Dispose();
                BinaryWriter BW = new BinaryWriter(new StreamWriter(@"C:\pics\" + i.ToString() + ".jpg").BaseStream);
                BW.Write(im);
                BW.BaseStream.Close();
                BW.Close();
                BW = null;
                WC = null;
               
            } catch(Exception er) {
                er=er;
                Console.WriteLine("ERROR: Can't d/l '" + googlethumbs[i] + "'.");
                continue;
            }
            l.Image = Image.FromFile(@"C:\pics\" + i.ToString() + ".jpg");
            l.Image = l.Image.GetThumbnailImage(((Size)gtsizes[i]).Width,((Size)gtsizes[i]).Height,null,new IntPtr(0));
            l.Width = l.Image.Width;
            l.Height = l.Image.Height;
            if(l.Height>largestY)
                largestY = l.Height;
            l.Location = new Point(x,y);
            x += l.Width + 5;
            if(x>800) {
                x = 5;
                y += largestY + 5;
            }
            l.Tag = i;
            Console.WriteLine(i);
            l.MouseDown += new MouseEventHandler(showstuff);
            this.Controls.Add(l);
            labels.Add(l);
            WC = null;
            Application.DoEvents();
        }
        Application.DoEvents();
        System.GC.Collect();
        Application.DoEvents();
        System.GC.Collect();
    }
   
    private void showstuff(object s,MouseEventArgs e) {
        if(System.Windows.Forms.MouseButtons.Right==e.Button) {
            Label l = (Label)s;
            Process.Start(@"C:\program files\internet explorer\iexplore.exe",(string)links[(int)l.Tag]);
        } else {
            Label l = (Label)s;
            WebClient WC = new WebClient();
            try {
                WC.OpenRead((string)thumbs[(int)l.Tag]).Close();
                WC.Dispose();
                Process.Start(@"C:\program files\internet explorer\iexplore.exe",(string)thumbs[(int)l.Tag]);
            } catch(Exception e44) {
                e44=e44;
                Process.Start(@"C:\program files\internet explorer\iexplore.exe",(string)links[(int)l.Tag]);
            }
        }
    }
   
    private void parse() {
        string k = resultpage;
        for(int i=0;i<k.Length;i++) {
            if(k[i]=='<'&&k[i+1]=='a') {
                Application.DoEvents();
                if(k.Substring(i,23)=="<a href=/imgres?imgurl=") {
                    i += 23;
                    string t = k.Substring(i,k.IndexOf("&",i)-i);
                    i = k.IndexOf("&imgrefurl=",i) + 11;
                    string l = k.Substring(i,k.IndexOf("&",i)-i);
                    i = k.IndexOf("img src=/images?q=tbn:",i) + 22;
                    string gt = "http://images.google.com/images?q=tbn:" + k.Substring(i,k.IndexOf(":",i)-i);
                    i = k.IndexOf("width=",i) + 6;
                    int w = Int32.Parse(k.Substring(i,k.IndexOf(" ",i)-i));
                    i = k.IndexOf("height=",i) + 7;
                    int h = Int32.Parse(k.Substring(i,k.IndexOf(">",i)-i));
                    gt += ":" + t;
                    googlethumbs.Add(gt);
                    thumbs.Add("http://" + t);
                    links.Add(l);
                    gtsizes.Add(new Size(w,h));
                }
            }
            Application.DoEvents();
            System.GC.Collect();
        }
    }
   
    private void WriteToFile() {
        StreamWriter SW = new StreamWriter("testgi.htm");
        SW.WriteLine(resultpage);
        SW.Close();
        SW = null;
    }
   
    public static void Main() {
        Application.Run(new ImageSearch());
    }
}

Comments

  1. 27 Aug 2005 at 23:11

    Greetings,
    I notice in your code sample that you force a Garbage Collection frequently and comment about 'Out of Memory' errors when calling Image.GetThummbnailImage(...);


    I, too, have been having serious problems with that Out of Memory error. I tried forcing a GC (and a .Dispose() beforehand), as you did here, but it did not help. I also notice that when the method is called, the memory usage on that process skyrockets way more than the size of the Image file. Still, I have excess physical memory and yet I get these errors.


    Can anyone enlighten me as to what's happening here or how to get around it? Is there a bad malloc in GDI+ or something? Is there a workaround someone has found?


    I'm in a bit of a pickle until I can get this working...


    Cheers

  2. 01 Jan 1999 at 00:00

    This thread is for discussions of A shell for Google's image search.

Leave a comment

Sign in or Join us (it's free).

Michael H

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

Want to stay in touch with what's going on? Follow us on twitter!