Search code examples
phpgdimagefilter

imagefilter to create CSS sprites


I'd like to automate creation of images for CSS sprites.

My goal is to convert a color thumbnail into black and white and merge it into one image with a color one on top and black at the bottom).

Here is what I have so far:

<?php
$image = imagecreatefrompng('test.png');

if($image && imagefilter($image , IMG_FILTER_GRAYSCALE))
{
    echo 'Image converted.';

    imagepng($image, 'test.png');
}
else
{
    echo 'Conversion failed.';
}

imagedestroy($image);
?>

Solution

  • <?php
    $image_path = 'test.png';
    $input_image = imagecreatefrompng($image_path);
    $image_info = getimagesize($image_path);
    $output_image = imagecreatetruecolor($image_info[0], $image_info[1] * 2);
    imagecopy ($output_image, $input_image, 0, 0, 0, 0, $image_info[0], $image_info[1]);
    if(imagefilter($input_image, IMG_FILTER_GRAYSCALE)) {
        echo 'Image converted.';
        imagecopy ($output_image, $input_image, 0, $image_info[1], 0, 0, $image_info[0], $image_info[1]);
        imagepng($output_image, 'test.png');
    } else {
        echo 'Conversion failed.';
    }
    imagedestroy($input_image);
    imagedestroy($output_image);
    ?>