Advertisement
Guest User

Untitled

a guest
May 25th, 2015
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. <?php
  2. class InlineImages {
  3. /** IE cannot display inline data larger than 32KiB
  4. also processing large images would take too much time */
  5. const SIZE_LIMIT = 32768;
  6.  
  7. /** Regular expression to find URL definitions in CSS file */
  8. const REGEXP = '/(background(-image)?|list-style(-image)?|cursor):\ ?url\(([\'\"]?([^\'\)]+)[\'\"]?)\)/im';
  9. const REGIND = 5; //index of matching parenthesis where URL can be found
  10.  
  11. /** Quotation character for CSS url() function
  12. - either ' or " (just in case you want to change it ;) */
  13. const QUOTE = '\''; //
  14.  
  15. private $path;
  16.  
  17. /**
  18. * Creates new instance of CSS image replacer
  19. *
  20. * @param [String] path where to look for images - URLs in CSS must be relative to this path!
  21. */
  22. public function __construct($path) {
  23. $this->path = $path;
  24. }
  25.  
  26. /**
  27. * Replace images in CSS file with inline data
  28. *
  29. * @param [String] CSS file content
  30. * @return [String] replaced CSS
  31. */
  32. public function process($data) {
  33. if (false !== preg_match_all(self::REGEXP, $data, $matches)) {
  34. $images = array();
  35. foreach ($matches[self::REGIND] as $index => $url) {
  36. $key = $matches[self::REGIND - 1][$index]; //URL including quotes (that must be removed from file as well)
  37. $filename = realpath($this->path . $url);
  38. if (false !== $filename && self::SIZE_LIMIT > filesize($filename)) {
  39. //get Base64-encoded content of the file
  40. $file = file_get_contents($filename);
  41. $base64 = base64_encode($file);
  42. //get Type of the file
  43. if (class_exists('finfo')) { //optional, requires PHP extension FileInfo (preferred)
  44. $finfo = new finfo(FILEINFO_MIME);
  45. $mime = $finfo->file($filename);
  46. $mime = explode(';', $mime)[0]; //returns also charset
  47. }
  48. elseif (function_exists('mime_content_type')) { //optional, requires PHP extension MimeType (deprecated)
  49. $mime = mime_content_type($filename);
  50. } else { //old way of detecting MIME from file extension
  51. preg_match('/\.([^\.]+)$/', $filename, $mime);
  52. $mime = 'image/' . $mime[1];
  53. }
  54. //save the content
  55. if (self::SIZE_LIMIT > count($base64)) { //base64 increses file size by ~20% - check the limit again
  56. $images[$key] = self::QUOTE . 'data:' . $mime . ';base64,' . $base64 . self::QUOTE;
  57. }
  58. }
  59. }
  60. if (count($images)) {
  61. $data = strtr($data, $images);
  62. }
  63. }
  64.  
  65. return $data;
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement