[英]Symfony Render Unreadable characters in twig
所以我对 Symfony 还很陌生,我试图在一个 twig 文件中呈现这个自定义验证码,但是 jpeg 以不可读的字符出现。 当我将其加载到常规 php 文件中时,图像没有问题。
在 AppExtension 文件中,我有以下内容,
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);
}
然后在我的树枝文件中,我有
{{ createImage() }}
它返回类似这样的字符: 9= f y{ @ O w_ j $ l| 6 [ b - 9(\\f8 _ Dž m+ Z sa$:u ' l!?
imagejpg
将结果直接输出到浏览器,因此图像是由 php 本身而不是由imagejpg
打印的,如果有道理的话。 此外,浏览器试图将其打印为文本,但它是二进制内容,这就是为什么输出被破坏以及为什么要发送Content-Type
标头的原因,以提示浏览器它是什么。
因此,该脚本旨在在其自己的请求中用作独立脚本。
以您想要的方式使用,如果您不想创建临时文件,您可以捕获输出并生成一个可以被浏览器正确解释的img
标签:
// 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.