|
1
|
|
|
<?php |
|
2
|
|
|
namespace nstdio\svg\output; |
|
3
|
|
|
use Mimey\MimeTypes; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Class ImageOutput |
|
7
|
|
|
* |
|
8
|
|
|
* @package nstdio\svg\output |
|
9
|
|
|
* @author Edgar Asatryan <[email protected]> |
|
10
|
|
|
*/ |
|
11
|
|
|
class ImageOutput implements ImageOutputInterface |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @var MimeTypes |
|
15
|
|
|
*/ |
|
16
|
|
|
private static $mime; |
|
17
|
|
|
|
|
18
|
150 |
|
public function __construct() |
|
19
|
|
|
{ |
|
20
|
150 |
|
self::$mime = new MimeTypes(); |
|
21
|
150 |
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @inheritdoc |
|
25
|
|
|
*/ |
|
26
|
|
|
public function imageFile($content, $name, $format, $override) |
|
27
|
|
|
{ |
|
28
|
|
|
$imagick = $this->createImagick($content, $format); |
|
29
|
|
|
|
|
30
|
|
|
$fileWriter = new FileOutput(); |
|
31
|
|
|
|
|
32
|
|
|
return $fileWriter->file($name, $imagick->getImageBlob(), $override); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param $content |
|
37
|
|
|
* @param $format |
|
38
|
|
|
* |
|
39
|
|
|
* @return \Imagick |
|
40
|
|
|
*/ |
|
41
|
|
|
private function createImagick($content, $format) |
|
42
|
|
|
{ |
|
43
|
|
|
$this->checkExtensionLoaded(); |
|
44
|
|
|
|
|
45
|
|
|
$imagick = new \Imagick(); |
|
46
|
|
|
|
|
47
|
|
|
$imagick->readImageBlob($content); |
|
48
|
|
|
try { |
|
49
|
|
|
$imagick->setImageFormat($format); |
|
50
|
|
|
} catch (\ImagickException $e) { |
|
51
|
|
|
throw new \InvalidArgumentException(sprintf("Invalid image format %s.", $format), 0, $e); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
return $imagick; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
private function checkExtensionLoaded() |
|
58
|
|
|
{ |
|
59
|
|
|
if (!extension_loaded('imagick')) { |
|
60
|
|
|
throw new \RuntimeException('Imagick extension is not loaded. If you access to php.ini try uncomment or add extension=php_imagick.so.'); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @inheritdoc |
|
66
|
|
|
*/ |
|
67
|
|
|
public function image($content, $format, $sendHeader) |
|
68
|
|
|
{ |
|
69
|
|
|
$imagick = $this->createImagick($content, $format); |
|
70
|
|
|
|
|
71
|
|
|
if ($sendHeader) { |
|
72
|
|
|
$this->trySendHeader($format); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
return $imagick->getImageBlob(); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
private function trySendHeader($format) |
|
79
|
|
|
{ |
|
80
|
|
|
if (!headers_sent()) { |
|
81
|
|
|
header($this->getContentType($format)); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
private function getContentType($format) |
|
86
|
|
|
{ |
|
87
|
|
|
return sprintf("Content-Type: %s", self::$mime->getMimeType($format)); |
|
88
|
|
|
} |
|
89
|
|
|
} |