Skip to content

Instantly share code, notes, and snippets.

@velizarn
Last active January 1, 2016 16:39
Show Gist options
  • Save velizarn/8172083 to your computer and use it in GitHub Desktop.
Save velizarn/8172083 to your computer and use it in GitHub Desktop.
When you have a number of small images that appear on a page it makes sense to use CSS sprites to speed-up the rendering of your web page. This has two advantages: It reduces the number of HTTP requests a browser has to make to download the images on your page; Speeds up the rendering of the images and the web-page due to limits on the number of…
<?php
error_reporting(E_ALL);
$images_to_load = array(
'C:/img-folder/01.jpg',
'C:/img-folder/02.jpg',
'C:/img-folder/03.jpg',
'C:/img-folder/04.jpg',
'C:/img-folder/05.jpg',
);
function load_jpeg($imgname, $width=100, $height=100)
{
/* Attempt to open */
$im = @imagecreatefromjpeg($imgname);
/* See if it failed */
if(!$im)
{
/* Create a black image */
$im = imagecreatetruecolor($width, $height);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}
return $im;
}
function create_sprite($images_to_load, $path_to_file=NULL)
{
if ($path_to_file === NULL) header('Content-Type: image/jpeg');
$imgs = array();
$wrapimg = @imagecreatetruecolor(sizeof($images_to_load)*100, 100)
or die('Cannot Initialize new GD image stream');
foreach ($images_to_load as $n => $_img)
{
$imgs[$n] = load_jpeg($_img);
imagecopy($wrapimg, $imgs[$n], $n*100, 0, 0, 0, 100, 100);
}
// create (and save) sprite image
imagejpeg($wrapimg, $path_to_file, 70);
reset($images_to_load);
foreach ($images_to_load as $n => $_img)
{
imagedestroy($imgs[$n]);
}
imagedestroy($wrapimg);
}
// ---------------------------------------------
create_sprite($images_to_load, __DIR__."/sprite.jpg");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment