Creating a QR Code with a centered Logo in PHP with PHP QR Code Generator

时间:2017-08-05 10:44:05

标签: php qr-code

I'm creating QR codes with PHP QR Code (http://phpqrcode.sourceforge.net/). It works well but now I need a free space for a custom graphic or logo in the center of it. And I want to do this without saving the image on the server. Has anyone a suggestion? What I've got so far is this:

<?php
     $param = $_GET['projectid']; 
     $divider = ",";

     $codeText = 'Projectname'.$divider.$param;

     // outputs image directly into browser, as PNG stream
     //QRcode::png($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)
     QRcode::png($codeText, false, QR_ECLEVEL_H, 9, 2, true );
?>

1 个答案:

答案 0 :(得分:1)

好的,我找到了解决方案。创建图像文件的临时文件,以插入徽标或任何您想要的内容。我在这里找到的代码只是一个非常小的变化http://ourcodeworld.com/articles/read/225/how-to-generate-qr-code-with-logo-easily-in-php-automatically 我在最后使用readfile()将所有内容直接推送到输出缓冲区。

<?php
        // user input        
        $param = $_GET['projectid']; 
        $divider = ",";

        // Path where the images will be saved
        $filepath = 'content/images/qr/qr-temp-image.png';
        // Image (logo) to be drawn
        $logopath = 'content/images/qr/qr-freespace.png';
        // we need to be sure ours script does not output anything!!!
        // otherwise it will break up PNG binary! 
        ob_start("callback");

        // text for the qr code
        $codeText = 'Projectname'.$divider.$param;

        // end of processing here
        $debugLog = ob_get_contents();
        ob_end_clean();

        // create a QR code and save it in the filepath
        QRcode::png($codeText, $filepath, QR_ECLEVEL_H, 9, 2, true );

        // Start DRAWING LOGO IN QRCODE

        $QR = imagecreatefrompng($filepath);

        // START TO DRAW THE IMAGE ON THE QR CODE
        $logo = imagecreatefromstring(file_get_contents($logopath));
        $QR_width = imagesx($QR);
        $QR_height = imagesy($QR);

        $logo_width = imagesx($logo);
        $logo_height = imagesy($logo);

        // Scale logo to fit in the QR Code
        $logo_qr_width = $QR_width/3;
        $scale = $logo_width/$logo_qr_width;
        $logo_qr_height = $logo_height/$scale;

        imagecopyresampled($QR, $logo, $QR_width/3, $QR_height/3, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);

        // Save QR code again, but with logo on it
        imagepng($QR,$filepath);
        // outputs image directly into browser, as PNG stream
        readfile($filepath);
?>