Guest User

Untitled

a guest
May 26th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Text.RegularExpressions;
  5. using HtmlAgilityPack;
  6.  
  7. namespace EmbedHtml
  8. {
  9. public class Embeder
  10. {
  11. private const int MAX_CONCURRENCY = 5;
  12.  
  13. public string Url { get; set; }
  14.  
  15. public Embeder(string url)
  16. {
  17. Url = url;
  18. }
  19.  
  20. public string Process()
  21. {
  22. var html = new WebClient().DownloadString(Url);
  23. var doc = new HtmlDocument();
  24. doc.LoadHtml(html);
  25.  
  26. var images = doc.DocumentNode.SelectNodes("//img");
  27. var imagesParallel = Enumerable.Range(0, images.Count).Select(i => images[i]).AsParallel().WithDegreeOfParallelism(MAX_CONCURRENCY);
  28.  
  29. imagesParallel.ForAll(img =>
  30. {
  31. var extension = Regex.Match(img.Attributes["src"].Value, "^.(.+)$");
  32. var imageUri = new Uri(new Uri(Url), img.Attributes["src"].Value);
  33.  
  34. var data = new WebClient().DownloadData(imageUri);
  35.  
  36. if (data != null && extension.Success)
  37. {
  38. var dataB64 = Convert.ToBase64String(data);
  39. img.Attributes["src"].Value = string.Format("data:image/{0};base64,{1}", extension.Value, dataB64);
  40. }
  41. });
  42.  
  43. return doc.DocumentNode.InnerHtml;
  44. }
  45. }
  46. }
Add Comment
Please, Sign In to add comment