1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link http://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license http://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\captcha; |
9
|
|
|
|
10
|
|
|
use yii\base\InvalidConfigException; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* ImagickDriver renders the CAPTCHA image based on the code using [ImageMagick](http://php.net/manual/en/book.imagick.php) library. |
14
|
|
|
* |
15
|
|
|
* @author Qiang Xue <[email protected]> |
16
|
|
|
* @since 2.1.0 |
17
|
|
|
*/ |
18
|
|
|
class ImagickDriver extends Driver |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* {@inheritdoc} |
22
|
|
|
*/ |
23
|
|
|
public function init() |
24
|
|
|
{ |
25
|
|
|
parent::init(); |
26
|
|
|
|
27
|
|
|
if (!extension_loaded('imagick') || !in_array('PNG', (new \Imagick())->queryFormats('PNG'), true)) { |
28
|
|
|
throw new InvalidConfigException('ImageMagick PHP extension with PNG support is required.'); |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* {@inheritdoc} |
34
|
|
|
*/ |
35
|
|
|
public function renderImage($code) |
36
|
|
|
{ |
37
|
|
|
$backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . str_pad(dechex($this->backColor), 6, 0, STR_PAD_LEFT)); |
38
|
|
|
$foreColor = new \ImagickPixel('#' . str_pad(dechex($this->foreColor), 6, 0, STR_PAD_LEFT)); |
39
|
|
|
|
40
|
|
|
$image = new \Imagick(); |
41
|
|
|
$image->newImage($this->width, $this->height, $backColor); |
42
|
|
|
|
43
|
|
|
$draw = new \ImagickDraw(); |
44
|
|
|
$draw->setFont($this->fontFile); |
45
|
|
|
$draw->setFontSize(30); |
46
|
|
|
$fontMetrics = $image->queryFontMetrics($draw, $code); |
47
|
|
|
|
48
|
|
|
$length = strlen($code); |
49
|
|
|
$w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1); |
50
|
|
|
$h = (int) $fontMetrics['textHeight'] - 8; |
51
|
|
|
$scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h); |
52
|
|
|
$x = 10; |
53
|
|
|
$y = round($this->height * 27 / 40); |
54
|
|
|
for ($i = 0; $i < $length; ++$i) { |
55
|
|
|
$draw = new \ImagickDraw(); |
56
|
|
|
$draw->setFont($this->fontFile); |
57
|
|
|
$draw->setFontSize((int) (mt_rand(26, 32) * $scale * 0.8)); |
58
|
|
|
$draw->setFillColor($foreColor); |
59
|
|
|
$image->annotateImage($draw, $x, $y, mt_rand(-10, 10), $code[$i]); |
60
|
|
|
$fontMetrics = $image->queryFontMetrics($draw, $code[$i]); |
61
|
|
|
$x += (int) $fontMetrics['textWidth'] + $this->offset; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$image->setImageFormat('png'); |
65
|
|
|
return $image->getImageBlob(); |
66
|
|
|
} |
67
|
|
|
} |