Skip to content

Instantly share code, notes, and snippets.

@slivero
Created October 7, 2011 14:02
Show Gist options
  • Save slivero/1270344 to your computer and use it in GitHub Desktop.
Save slivero/1270344 to your computer and use it in GitHub Desktop.
Demonstration of process forking in PHP to speed up image resizing
<?php
/**
* Create a thumbnail image from the specified file
*
* @param int $height output image height
* @param int $width output image width
*/
function create_preview($height, $width)
{
//Input image
$img = 'test.jpg';
//Output image
$new_img = 'test -'.$width.'x'.$height.'.jpg';
//get the current image size
list($full_width, $full_height) = getimagesize($img) ;
//Create a blank image to load in the new resized image
$tn = imagecreatetruecolor($width, $height) ;
//Load the original file
$image = imagecreatefromjpeg($img) ;
//Do the crop
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $full_width, $full_height) ;
//Save the file
imagejpeg($tn, $new_img, 100);
}
// The thumbnail sizes to be generated
$image_sizes = array(
array(100,100),
array(200, 200),
array(300, 300),
array(400, 400),
array(500, 500),
array(1000, 1000)
);
//Counter for number of processes
$i = 1;
//Loop through the image sizes but this time fork a process for each size.
foreach($image_sizes as $image_size)
{
//Fork a process
$pid = pcntl_fork();
//if we're in a child thread then grab an image size and process it.
if (!$pid)
{
echo 'starting child ', $i, PHP_EOL;
create_preview($image_size[0], $image_size[1]);
//Die otherwise the process will continue to loop and each process will
//create all the thumbnails
die();
}
$i++;
}
//Wait for all the subprocesses to complete to avoid zombie processes
foreach($image_sizes as $image_size)
{
pcntl_wait($status);
}
?>
<?php
/**
* Create a thumbnail image from the specified file
*
* @param int $height output image height
* @param int $width output image width
*/
function create_preview($height, $width)
{
//Input image
$img = 'test.jpg';
//Output image
$new_img = 'test -'.$width.'x'.$height.'.jpg';
//get the current image size
list($full_width, $full_height) = getimagesize($img) ;
//Create a blank image to load in the new resized image
$tn = imagecreatetruecolor($width, $height) ;
//Load the original file
$image = imagecreatefromjpeg($img) ;
//Do the crop
imagecopyresampled($tn, $image, 0, 0, 0, 0, $width, $height, $full_width, $full_height) ;
//Save the file
imagejpeg($tn, $new_img, 100);
}
// The thumbnail sizes to be generated
$image_sizes = array(
array(100,100),
array(200, 200),
array(300, 300),
array(400, 400),
array(500, 500),
array(1000, 1000)
);
// Loop through the images sequentially
foreach($image_sizes as $image_size)
{
create_preview($image_size[0], $image_size[1]);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment