Last active
July 5, 2016 21:39
-
-
Save Mat-Moo/57b0caa97489c3223c3de55b576fa8c5 to your computer and use it in GitHub Desktop.
Need to take a bunch of pngs and create a single png that can be css animated?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* User: Matthew Augier | |
* Data Product Services Ltd. | |
* PHP command line code to convert a sequence of PNG's into a single png file | |
* which can be used with css to play it as an animation | |
* Date: 05/07/2016 | |
* Time: 21:46 | |
*/ | |
function human_filesize($bytes, $decimals = 2) { | |
$sz = 'BKMGTP'; | |
$factor = floor((strlen($bytes) - 1) / 3); | |
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor]; | |
} | |
// help! | |
if (count($argv) == 1) { | |
die("php make_png_sequence.php [folder] [compression 0-9, 0=none]"); | |
} | |
// get the path to look for from the command line | |
$folder = isset($argv[1]) ? $argv[1] : 'mooo'; | |
if ( ! file_exists($folder)) die("Unable to find the folder " . $folder); | |
$compression = isset($argv[2]) ? $argv[2] : 2; | |
// get a list of png files | |
$files = []; | |
foreach (glob($folder . "/*.png") as $filename) { | |
$files[] = $filename; | |
} | |
// sort just in casef | |
sort($files); | |
// load the first file to get info | |
$frames = count($files); | |
$info = getimagesize($files[0]); | |
list($width, $height) = $info; | |
print "Image details - Width:{$width}, Height:{$height}, Frames:{$frames} \r\n"; | |
$out_width = $width * $frames; | |
print "Output image - Width:{$out_width}, Height:{$height}\r\n"; | |
$css_frames = $frames - 1 ; | |
$bg_pos = $out_width - $width; | |
print "CSS helpers - #id {animation: play 5s steps({$css_frames}) infinite;} @keyframes play {100% { background-position: -{$bg_pos}px; }}\r\n"; | |
// increase the memory limit due to image size | |
ini_set('memory_limit','512M'); | |
$out_image = imagecreatetruecolor($out_width, $height); | |
$offset = 0; | |
foreach($files as $file){ | |
$frame = imagecreatefrompng($file); | |
imagecopy($out_image, $frame, $offset, 0, 0, 0, $width, $height); | |
$offset += $width; | |
} | |
// save the image out | |
imagepng($out_image, $folder . '.png', $compression); | |
print "Completed writing {$folder}.png - filesize " . human_filesize(filesize($folder . '.png')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Folder is the folder with a sequence of png images, output will be the folder name .png - Note this is designed to run as a command line, would need work to use for anything production wise