Search code examples
phpphp-imagine

How to pad thumbnails with imagine library


I am using imagine library to create thumbnails for images. It is as simple as this.

$size = new \Imagine\Image\Box(240, 180);
$imagine->open($source_path)->thumbnail($size, 'inset')->save($target_path);

the library provides two modes : inset and outbound. in inset mode the image is resized down but it does not fill the thumbnail size. So I need to pad it to fill the target size. Is there an easy way to do this using library functions ?


Solution

  • I have managed to pad thumbnails with following function.

    function pad(\Imagine\Gd\Imagine $img, \Imagine\Image\Box $size, $fcolor='#000', $ftransparency = 100)
        {
            $tsize = $img->getSize();
            $x = $y = 0;
            if ($size->getWidth() > $tsize->getWidth()) {
                $x =  round(($size->getWidth() - $tsize->getWidth()) / 2);
            } elseif ($size->getHeight() > $tsize->getHeight()) {
                $y = round(($size->getHeight() - $tsize->getHeight()) / 2);
            }
            $pasteto = new \Imagine\Image\Point($x, $y);
            $imagine = new \Imagine\Gd\Imagine();
            $color = new \Imagine\Image\Color($fcolor, $ftransparency);
            $image = $imagine->create($size, $color);
    
            $image->paste($img, $pasteto);
    
            return $image;
        }