Contao\GdImage::fromDimensions PHP Method

fromDimensions() public static method

Get the GD image object for the specified dimensions
public static fromDimensions ( integer $width, integer $height ) : static
$width integer The image width
$height integer The image height
return static The GD image object
    public static function fromDimensions($width, $height)
    {
        $image = imagecreatetruecolor($width, $height);
        $arrGdInfo = gd_info();
        $strGdVersion = preg_replace('/[^0-9.]+/', '', $arrGdInfo['GD Version']);
        // Handle transparency (GDlib >= 2.0 required)
        if (version_compare($strGdVersion, '2.0', '>=')) {
            imagealphablending($image, false);
            imagefill($image, 0, 0, imagecolorallocatealpha($image, 0, 0, 0, 127));
            imagesavealpha($image, true);
        }
        return new static($image);
    }

Usage Example

Example #1
0
 /**
  * Tests the copyTo() method.
  */
 public function testCopyTo()
 {
     $image = imagecreatetruecolor(100, 100);
     // Whole image black
     imagefill($image, 0, 0, imagecolorallocatealpha($image, 0, 0, 0, 0));
     $image = new GdImage($image);
     $target = GdImage::fromDimensions(100, 100);
     $image->copyTo($target, 10, 10, 80, 80);
     $this->assertEquals(['red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => 0], imagecolorsforindex($target->getResource(), imagecolorat($target->getResource(), 50, 50)), 'Center should be black');
     $this->assertEquals(['red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => 0], imagecolorsforindex($target->getResource(), imagecolorat($target->getResource(), 10, 10)), '10 pixel from left top should be black');
     $this->assertEquals(['red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => 0], imagecolorsforindex($target->getResource(), imagecolorat($target->getResource(), 89, 89)), '10 pixel from right bottom should be black');
     $this->assertEquals(127, imagecolorsforindex($target->getResource(), imagecolorat($target->getResource(), 0, 0))['alpha'], 'Left top pixel should be transparent');
     $this->assertEquals(127, imagecolorsforindex($target->getResource(), imagecolorat($target->getResource(), 99, 99))['alpha'], 'Bottom right pixel should be transparent');
     $this->assertEquals(127, imagecolorsforindex($target->getResource(), imagecolorat($target->getResource(), 9, 9))['alpha'], '9 pixel from left top should be transparent');
     $this->assertEquals(127, imagecolorsforindex($target->getResource(), imagecolorat($target->getResource(), 90, 90))['alpha'], '9 pixel from bottom right should be transparent');
 }