Skip to content

PHP Fatal error: Uncaught TypeError: imagecopyresampled(): Argument #1 ($dst_image) must be of type GdImage, bool given in /Users/gekongfei/Desktop/generate_qrcode/generate2.php:47 #141

@tennessine

Description

@tennessine
<?php

require_once './vendor/autoload.php';

use chillerlan\QRCode\{QRCode, QROptions};
use chillerlan\QRCode\Common\EccLevel;
use chillerlan\QRCode\Data\QRMatrix;
use chillerlan\QRCode\Output\{QRGdImage, QRCodeOutputException};

class QRImageWithLogo extends QRGdImage{

	/**
	 * @param string|null $file
	 * @param string|null $logo
	 *
	 * @return string
	 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
	 */
	public function dump(string $file = null, string $logo = null):string{
		// set returnResource to true to skip further processing for now
		$this->options->returnResource = true;

		// of course you could accept other formats too (such as resource or Imagick)
		// i'm not checking for the file type either for simplicity reasons (assuming PNG)
		if(!is_file($logo) || !is_readable($logo)){
			throw new QRCodeOutputException('invalid logo');
		}

		// there's no need to save the result of dump() into $this->image here
		parent::dump($file);

		$im = imagecreatefrompng($logo);

		// get logo image size
		$w = imagesx($im);
		$h = imagesy($im);

		// set new logo size, leave a border of 1 module (no proportional resize/centering)
		$lw = ($this->options->logoSpaceWidth - 2) * $this->options->scale;
		$lh = ($this->options->logoSpaceHeight - 2) * $this->options->scale;

		// get the qrcode size
		$ql = $this->matrix->size() * $this->options->scale;

		// scale the logo and copy it over. done!

		imagecopyresampled($this->image, $im, ($ql - $lw) / 2, ($ql - $lh) / 2, 0, 0, $lw, $lh, $w, $h);

		$imageData = $this->dumpImage();

		if($file !== null){
			$this->saveToFile($imageData, $file);
		}

		if($this->options->imageBase64){
			$imageData = $this->base64encode($imageData, 'image/'.$this->options->outputType);
		}

		return $imageData;
	}

}

$options = new QROptions([
	'version'             => 5,
	'eccLevel'            => EccLevel::H,
	'imageBase64'         => false,
	'addLogoSpace'        => true,
	'logoSpaceWidth'      => 13,
	'logoSpaceHeight'     => 13,
	'scale'               => 6,
	'imageTransparent'    => false,
	'drawCircularModules' => true,
	'circleRadius'        => 0.45,
	'keepAsSquare'        => [QRMatrix::M_FINDER, QRMatrix::M_FINDER_DOT],
]);

$qrcode = new QRCode($options);
$qrcode->addByteSegment('https://github.com');

$qrOutputInterface = new QRImageWithLogo($options, $qrcode->getMatrix());

$qrOutputInterface->dump(NULL, __DIR__.'/logo.png');

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions