Search code examples
phpqr-code

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


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 );
?>

Solution

  • Ok, I've found a solution. Where a image file is created temporaray to insert the the logo or whatever you want. I't just a very small change form the code found here http://ourcodeworld.com/articles/read/225/how-to-generate-qr-code-with-logo-easily-in-php-automatically I'm using readfile() at the end to push everything directly to the output buffer.

    <?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);
    ?>