Advertisement
rakoczyn

HTMLImageParser

Mar 28th, 2012
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using System.Text.RegularExpressions;
  8. using System.Drawing;
  9. using System.Windows.Forms;
  10.  
  11. namespace Memo
  12. {
  13.     static class HTMLImageParser
  14.     {
  15.  
  16.  
  17.  
  18.         static public List<Image> Parse(string URL)
  19.         {
  20.             List<string> imageLinksCollection = new List<string>();
  21.  
  22.             WebRequest wr = WebRequest.Create(URL);
  23.             WebClient wc = new WebClient();
  24.             wc.Proxy = null;
  25.  
  26.             string fileS;
  27.  
  28.             using (var file = new StreamReader(wr.GetResponse().GetResponseStream()))
  29.             {
  30.                 fileS = file.ReadToEnd();
  31.             }
  32.  
  33.  
  34.            
  35.             Regex jpgReg = new Regex(@"<\s*img [^\>]*src\s*=\s*([""\'])(.*?)\1", RegexOptions.IgnoreCase);
  36.             Match jpg = jpgReg.Match(fileS);
  37.             while (jpg.Success)
  38.             {
  39.                 string s = jpg.Value;
  40.                 if (s.Contains("http"))
  41.                 {
  42.                     s = s.Substring(s.IndexOf("http"), s.IndexOf("\"", s.IndexOf("http"), s.Length - s.IndexOf("http")) - s.IndexOf("http"));
  43.                     imageLinksCollection.Add(s);
  44.                 }
  45.                 jpg = jpg.NextMatch();
  46.             }
  47.  
  48.             var imagesLinks = imageLinksCollection.Distinct();
  49.  
  50.             List<Image> Images = new List<Image>();
  51.  
  52.  
  53.  
  54.  
  55.             foreach (string link in imagesLinks)
  56.             {
  57.                 try
  58.                 {
  59.                     byte[] bFile = wc.DownloadData(link);
  60.                     MemoryStream ms = new MemoryStream(bFile);
  61.                     Images.Add(Image.FromStream(ms));
  62.                 }
  63.                 catch (Exception)
  64.                 {
  65.  
  66.  
  67.                 }
  68.  
  69.             }
  70.  
  71.             return Images;
  72.  
  73.         }
  74.  
  75.     }
  76.  
  77.  
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement