View source
<?php
namespace Drupal\image_captcha\StreamedResponse;
use Drupal\Core\Config\ImmutableConfig;
use Symfony\Component\HttpFoundation\StreamedResponse;
class CaptchaFontPreviewStreamedResponse extends StreamedResponse {
protected $config;
protected $token;
public function __construct(ImmutableConfig $config, $token, $callback = NULL, $status = 200, $headers = []) {
parent::__construct(NULL, $status, $headers);
$this->config = $config;
$this->token = $token;
}
public function sendContent() {
if ($this->token == 'BUILTIN') {
$font = 'BUILTIN';
}
else {
$fonts = $this->config
->get('image_captcha_fonts_preview_map_cache');
if (!isset($fonts[$this->token])) {
return 'bad token';
}
$font = $fonts[$this->token]['uri'];
if (!is_file($font) || !is_readable($font)) {
return 'bad font';
}
}
$width = 120;
$text = 'AaBbCc123';
$font_size = 14;
$height = 2 * $font_size;
$image = imagecreatetruecolor($width, $height);
if (!$image) {
return NULL;
}
$background_color = imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $width, $height, $background_color);
if ($font == 'BUILTIN') {
imagestring($image, 5, 1, 0.5 * $height - 10, $text, $color);
}
else {
imagettftext($image, $font_size, 0, 1, 1.5 * $font_size, $color, realpath($font), $text);
}
$this->headers
->set('Content-Type', 'image/png');
imagepng($image);
imagedestroy($image);
}
}