简体   繁体   中英

Symfony Render Unreadable characters in twig

So I'm fairly new to Symfony and I'm trying to render this custom captcha in a twig file, but the jpeg comes out in unreadable characters. When I load this up in a regular php file, the image comes out with no problem.

In an AppExtension file, I have the following,

public function getFunctions() {
 return ['createImage' => new \Twig_SimpleFunction('createImage', [$this, 'createImage']),]
}

function createImage()
    {
        $md5_hash = md5(rand(0,999));
        $captcha=substr($md5_hash, 15,5);

        $_SESSION['captcha'] =$captcha;

        $width = 200;
        $height = 50;

        $image = ImageCreate($width,$height);   

        $white = imagecolorallocate($image, 255, 255, 255);
        $black = imagecolorallocate($image, 0, 0, 0);
        $green = imagecolorallocate($image, 0, 255, 0);
        $brown = imagecolorallocate($image, 139, 69, 19);
        $orange = imagecolorallocate($image, 204, 204, 204);
        $grey = imagecolorallocate($image, 204, 204, 204);

        imagefill($image, 0, 0, $black);

        $font = __DIR__ . '/font.ttf';          
        imagettftext($image, 25, 10, 45, 45, $white, $font, $captcha);

        header("Content-Type: image/jpeg");

        html_entity_decode(imagejpeg($image));
        imagedestroy($image);       

    }

and then in my twig file, I have

{{ createImage() }}

It returns characters similar to this: 9= f y{ @ O w_ j $ l| 6 [ b - 9(\\f8 _ Dž m+ Z sa$:u ' l!?

imagejpg outputs the result directly to the browser so the image is being printed by php itself and not by twig, if that makes sense. In addition, the browser is trying to print it as text, but it's binary content that's why the output is mangled and why a Content-Type header is sent along, to hint the browser on what it is.

So that script is meant to be used as a standalone script in its own request.

To be used in the way you intend, and if you don't want to create a temporary file, you can capture the output and generate a img tag that can be correctly interpreted by the browser:

// Start buffering the output
ob_start();
imagettftext($image, 25, 10, 45, 45, $white, $font, $captcha);
imagejpeg($image);
imagedestroy($image);
// Get the data
$output = ob_get_clean();

// Encode in base64
$encodedImage = base64_encode($output);

// Create a img tag and inline the image
$img = "<img src='data:image/jpeg;base64, $encodedImage' />";

// Return the img tag to Twig
return $img;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM