버전 1.0

sharpdevelop/googleImageSearch 2015. 9. 6. 18:37


사용된 프로그래밍 툴 다운로드 :

SharpDevelop 4.4 http://www.icsharpcode.net/OpenSource/SD/Download/


소스파일 :googleImageSearch1_src.zip



실행파일 :googleImageSearch1_Debug.zip




1. 화면 디자인




2. 메인코드


/*
 * Created by SharpDevelop.
 * Date     : 2015-08-22
 * Time     : 오전 12:04
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace googleImageSearch1
{
    /// <summary>
    /// Description of MainForm.
    /// </summary>
    public partial class MainForm : Form
    {
        public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            
            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
        }
        
        void MainFormLoad(object sender, EventArgs e)
        {
            //1. url 대입
            //txtUrl.Text ="https://www.google.co.kr/search?q=%EA%B9%80%EC%82%AC%EB%9E%91&biw=1280&bih=895&source=lnms&tbm=isch&sa=X&ved=0CAYQ_AUoAWoVChMIvPDvrYa5xwIVxiiUCh3_SA24";//김사랑
            textBox1.Text="설현"//기본값

        }
        
        void Button1Click(object sender, EventArgs e)
        {
            textBox2.Text="https://www.google.co.kr/search?q="
                          + textBox1.Text
                       + "&biw=1280&bih=895&source=lnms&tbm=isch&sa=X&ved=0CAYQ_AUoAWoVChMIrJze3Ne5xwIVJOemCh2BgAdd";
                
            //2. 구글에 이미지 검색요청 해서 응답 받아오기
            
            //http://findfun.tistory.com/44
            WebRequest request = WebRequest.Create(textBox2.Text);
            request.Credentials = CredentialCache.DefaultCredentials;
            
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            
            Encoding encode;
            if (response.CharacterSet.ToLower() == "utf-8") { encode = Encoding.UTF8; }
            else { encode = Encoding.Default; }
            
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, encode);
 
            string responseFromServer = reader.ReadToEnd();            


            dataStream.Close();
            reader.Close();
            textBox3.Text=responseFromServer;
            
            
            //-------------------------
            
            //XmlDocument doc = new XmlDocument();
            //doc.LoadXml(responseFromServer);
            //XmlNodeList results = doc.SelectNodes("//img/@src");
            
            //http://kaliko.com/blog/extract-image-tags-from-html-in-c/
            List<string> images = new List<string>();
            string pattern = @"<(img)\b[^>]*>"// img 태그 찾기

            Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            MatchCollection matches = rgx.Matches(responseFromServer);
            
            textBox4.Text="";
            imageList1.Images.Clear();
            imageList1.ImageSize = new Size(120120);

            listView1.Clear();
            listView1.View = View.LargeIcon;

            XmlDocument doc = new XmlDocument();
            int count=0;
            for(int i=0, l=matches.Count; i<l; i++) {
                
                // 위에서 가져온 <img ...> 태그 형태에 </img>태그를 붙여서
                // xml 태그 형태로 만든다음
                doc.LoadXml(matches[i].Value + "</img>");  
                
                
                //doc.SelectNodes("//img/@src") 를 이용해서 img 태그의  src 속성값만 뽑아와서
                
                //출처 : http://stackoverflow.com/questions/1100156/how-to-select-nodes-with-xpath-in-c
                foreach (XmlNode node in doc.SelectNodes("//img/@src")){
                    
                    //만일 이미지 src 주소가 https://encrypted- 로 시작하면 그값들만 
                    //imglist1 과 listview1 에 추가함.
                    if ((node.InnerText).Contains("https://encrypted-")){  
                        
                        images.Add(node.InnerText);
                        textBox4.Text +=  node.InnerText + "\r\n";
                        //------------------------------
                        //출처 : http://www.devpia.com/Maeul/Contents/Detail.aspx?BoardID=17&MaeulNo=8&no=111893&ref=111788
                        // 이미지 url을 imaglist1에 넣기
                        byte[] buffer = null;
                        System.IO.MemoryStream ms = new System.IO.MemoryStream();
                        System.Net.WebClient wc = new System.Net.WebClient();

                        buffer = wc.DownloadData(node.InnerText);

                        ms.Write(buffer, 0, buffer.Length);
                        imageList1.Images.Add(new Bitmap(ms));
                        //--------------------------

                        int idx = imageList1.Images.Keys.Count-1;
                        imageList1.Images.SetKeyName(idx, "");
                        listView1.Items.Add(count.ToString(),idx);
                        
                        listView1.LargeImageList = imageList1;
                        count++;
                    }
                }
                doc.RemoveAll();
            }            
          //MessageBox.Show(imageList1.Images.Count.ToString());
        }
        
    }
}


3. 실행결과 캡쳐




'sharpdevelop > googleImageSearch' 카테고리의 다른 글

버전 2.0  (1) 2015.09.07
: