Strict Standards: gmmktime(): You should be using the time() function instead in /home/richard3/public_html/index.php on line 20

Strict Standards: mktime(): You should be using the time() function instead in /home/richard3/public_html/index.php on line 20

Warning: Cannot modify header information - headers already sent by (output started at /home/richard3/public_html/index.php:20) in /home/richard3/public_html/index.php on line 25
Innvo.com: Creating CSS Sprites with PHP

Creating CSS Sprites with PHP

Page last updated on 2011 / 04 / 09

When you have a number of small images that appear on a page, or a number of pages that you know one particular client is going to visit that include these small images, it makes sense to use CSS sprites to speed-up the rendering of your web page.

This has two advantages, namely:

The slight downside is that you may make a CSS sprite that contains images that don't appear on a particular page, and therefore the client doesn't need. Some consideration has to be put into these situations to weigh the pro's and con's of using a sprite.

A fairly comprehensive analysis of using sprites can be found at css-sprites.com.

Using PHP to Create Sprites

It's very easy to create a sprite using PHP, which can generate a single image from a collection of images, and also generate the CSS for you. This is a huge timesaver if you intend to make a number of sprites.

The following simple class will perform the following upon initiating the class:

  1. <?php
  2.  
  3. class images_to_sprite
  4. {
  5. function images_to_sprite($folder,$output,$x,$y)
  6. {
  7. $this->folder = ($folder ? $folder : 'myfolder'); // Folder name to get images from, i.e. C:\\myfolder or /home/user/Desktop/folder
  8. $this->filetypes = array('jpg'=>true,'png'=>true,'jpeg'=>true,'gif'=>true); // Acceptable file extensions to consider
  9. $this->output = ($output ? $output : 'mysprite'); // Output filenames, mysprite.png and mysprite.css
  10. $this->x = $x; // Width of images to consider
  11. $this->y = $y; // Heigh of images to consider
  12. $this->files = array();
  13. }
  14.  
  15. function create_sprite()
  16. {
  17. $basedir = $this->folder;
  18. $files = array();
  19. // Read through the directory for suitable images
  20. if($handle = opendir($this->folder))
  21. {
  22. while (false !== ($file = readdir($handle)))
  23. {
  24. $split = explode('.',$file);
  25. // Ignore non-matching file extensions
  26. if($file[0] == '.' || !isset($this->filetypes[$split[count($split)-1]]))
  27. continue;
  28. // Get image size and ascertain it has the correct dimensions
  29. $output = getimagesize($this->folder.'/'.$file);
  30. if($output[0] != $this->x && $output[1] != $this->y)
  31. continue;
  32. // Image will be added to sprite, add to array
  33. $this->files[$file] = $file;
  34. }
  35. closedir($handle);
  36. }
  37. // yy is the height of the sprite to be created, basically X * number of images
  38. $this->yy = $this->y * count($this->files);
  39. $im = imagecreatetruecolor($this->x,$this->yy);
  40. // Add alpha channel to image (transparency)
  41. imagesavealpha($im, true);
  42. $alpha = imagecolorallocatealpha($im, 0, 0, 0, 127);
  43. imagefill($im,0,0,$alpha);
  44.  
  45. // Append images to sprite and generate CSS lines
  46. $i = $ii = 0;
  47. $fp = fopen($this->output.'.css','w');
  48. fwrite($fp,'.'.$this->output.' { width: '.$this->x.'px; height: '.$this->y.'px; background-image: url('.$this->output.'.png); text-align:center; }'."\n");
  49. foreach($this->files as $key => $file)
  50. {
  51. fwrite($fp,'.'.$this->output.(++$ii).' { background-position: -0px -'.($this->y*$i).'px; }'."\n");
  52. $im2 = imagecreatefrompng($this->folder.'/'.$file);
  53. imagecopy($im,$im2,0,($this->y*$i),0,0,$this->x,$this->y);
  54. $i++;
  55. }
  56. fclose($fp);
  57. imagepng($im,$this->output.'.png'); // Save image to file
  58. imagedestroy($im);
  59. }
  60. }
  61.  
  62. $class = new images_to_sprite('imagefolder','sprite',63,63);
  63. $class->create_sprite();
  64.  
  65. ?>

There is no error-checking whatsoever in this script, so if you plan to have it on a production server you should consider what could go wrong, i.e. folder does not exist or there are no images in the folder.

Otherwise it is quite straight-forward and should prove to be a time-saver in creating sprites.


Previous Article
Creating a Directory Tree with PHP & MySQL (Part 2)





Tweet