Menu

#5 return image as a base64 encoded string

Unstable (example)
open
nobody
None
5
2021-05-02
2021-05-02
aducom
No

I was not able to get the image as a base64 string so I made some changes in qrimage.php:

       //----------------------------------------------------------------------
        public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) 
        {
            $image = self::image($frame, $pixelPerPoint, $outerFrame);
            $r='';
            if ($filename === false) {
                Header("Content-type: image/png");
                ImagePng($image);
            } else {
                if($saveandprint===TRUE){
                    ImagePng($image, $filename);
                    header("Content-type: image/png");
                    ImagePng($image);
                }else{
                    if($filename=='*') {
                       ob_start();
                       ImagePng($image);
                       $r = base64_encode(ob_get_contents());
                       ob_end_clean();
                    } else { 
                       ImagePng($image, $filename);
                    } 
                }
            }

            ImageDestroy($image);
            return $r;
        }

And in qrencode.php

        //----------------------------------------------------------------------
        public function encodePNG($intext, $outfile = false,$saveandprint=false) 
        {
            try {

                ob_start();
                $tab = $this->encode($intext);
                $err = ob_get_contents();
                ob_end_clean();

                if ($err != '')
                    QRtools::log($outfile, $err);

                $maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin));

                return QRimage::png($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint);

            } catch (Exception $e) {

                QRtools::log($outfile, $e->getMessage());

            }
        }
    }

The effect is that if you use * as filename that you get the image as a encoded string:

        $img= QRcode::png('PHP QR Code :)','*');
        $r='<img width="100" src="data:image/png;base64,'.$img.'"/>';   

The changes apply to the png, but can be applied to the jpg as well in the similar way.

Discussion


Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.