From 132520b0d0e9314d108eeb6459fada0aa811b1eb Mon Sep 17 00:00:00 2001 From: smiley Date: Tue, 19 Sep 2023 13:22:00 +0200 Subject: [PATCH] :sparkles: SVG to raster conversion example --- examples/imagickConvertSVGtoPNG.php | 111 ++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 examples/imagickConvertSVGtoPNG.php diff --git a/examples/imagickConvertSVGtoPNG.php b/examples/imagickConvertSVGtoPNG.php new file mode 100644 index 000000000..40942d4ad --- /dev/null +++ b/examples/imagickConvertSVGtoPNG.php @@ -0,0 +1,111 @@ + + * @copyright 2023 smiley + * @license MIT + */ + +use chillerlan\QRCode\Data\QRMatrix; +use chillerlan\QRCode\Output\QRMarkupSVG; +use chillerlan\QRCode\Output\QROutputInterface; +use chillerlan\QRCode\QRCode; +use chillerlan\QRCode\QROptions; + +require_once __DIR__.'/../vendor/autoload.php'; + +class SVGConvert extends QRMarkupSVG{ + + /** @inheritDoc */ + protected function header():string{ + [$width, $height] = $this->getOutputDimensions(); + + $header = sprintf( + '%6$s', + $this->options->cssClass, + $this->getViewBox(), + $this->options->svgPreserveAspectRatio, + ($width * $this->scale), + ($height * $this->scale), + $this->options->eol + ); + + if($this->options->svgAddXmlHeader){ + $header = sprintf('%s%s', $this->options->eol, $header); + } + + return $header; + } + + /** @inheritDoc */ + public function dump(string $file = null):string{ + $base64 = $this->options->outputBase64; + // we don't want the SVG in base64 + $this->options->outputBase64 = false; + + $svg = $this->createMarkup($file !== null); + + // now convert the output + $im = new Imagick; + $im->readImageBlob($svg); + $im->setImageFormat($this->options->imagickFormat); + + $imageData = $im->getImageBlob(); + + $this->saveToFile($imageData, $file); + + if($base64){ + // use finfo to guess the mime type + $imageData = $this->toBase64DataURI($imageData, (new finfo(FILEINFO_MIME_TYPE))->buffer($imageData)); + } + + return $imageData; + } + +} + + +// SVG from the basic example +$options = new QROptions; + +$options->version = 7; +$options->outputType = QROutputInterface::CUSTOM; +$options->outputInterface = SVGConvert::class; +$options->imagickFormat = 'png32'; +$options->scale = 20; +$options->outputBase64 = false; +$options->drawLightModules = true; +$options->markupDark = ''; +$options->markupLight = ''; +$options->drawCircularModules = true; +$options->circleRadius = 0.4; +$options->connectPaths = true; +$options->keepAsSquare = [ + QRMatrix::M_FINDER_DARK, + QRMatrix::M_FINDER_DOT, + QRMatrix::M_ALIGNMENT_DARK, +]; +$options->svgDefs = ' + + + + + + + + + '; + + +// render the SVG and convert to the desired ImageMagick format +$image = (new QRCode($options))->render('https://www.youtube.com/watch?v=dQw4w9WgXcQ'); + +header('Content-type: image/png'); + +echo $image;