PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php

http://github.com/drupal/drupal
PHP | 469 lines | 243 code | 36 blank | 190 comment | 43 complexity | 08a1ff1ef8e1db58887340d116c42d5c MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. namespace Drupal\system\Plugin\ImageToolkit;
  3. use Drupal\Component\Utility\Color;
  4. use Drupal\Core\Config\ConfigFactoryInterface;
  5. use Drupal\Core\File\Exception\FileException;
  6. use Drupal\Core\File\FileSystemInterface;
  7. use Drupal\Core\Form\FormStateInterface;
  8. use Drupal\Core\ImageToolkit\ImageToolkitBase;
  9. use Drupal\Core\ImageToolkit\ImageToolkitOperationManagerInterface;
  10. use Drupal\Core\StreamWrapper\StreamWrapperInterface;
  11. use Drupal\Core\StreamWrapper\StreamWrapperManager;
  12. use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
  13. use Psr\Log\LoggerInterface;
  14. use Symfony\Component\DependencyInjection\ContainerInterface;
  15. /**
  16. * Defines the GD2 toolkit for image manipulation within Drupal.
  17. *
  18. * @ImageToolkit(
  19. * id = "gd",
  20. * title = @Translation("GD2 image manipulation toolkit")
  21. * )
  22. */
  23. class GDToolkit extends ImageToolkitBase {
  24. /**
  25. * A GD image resource.
  26. *
  27. * @var resource|null
  28. */
  29. protected $resource = NULL;
  30. /**
  31. * Image type represented by a PHP IMAGETYPE_* constant (e.g. IMAGETYPE_JPEG).
  32. *
  33. * @var int
  34. */
  35. protected $type;
  36. /**
  37. * Image information from a file, available prior to loading the GD resource.
  38. *
  39. * This contains a copy of the array returned by executing getimagesize()
  40. * on the image file when the image object is instantiated. It gets reset
  41. * to NULL as soon as the GD resource is loaded.
  42. *
  43. * @var array|null
  44. *
  45. * @see \Drupal\system\Plugin\ImageToolkit\GDToolkit::parseFile()
  46. * @see \Drupal\system\Plugin\ImageToolkit\GDToolkit::setResource()
  47. * @see http://php.net/manual/function.getimagesize.php
  48. */
  49. protected $preLoadInfo = NULL;
  50. /**
  51. * The StreamWrapper manager.
  52. *
  53. * @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
  54. */
  55. protected $streamWrapperManager;
  56. /**
  57. * The file system.
  58. *
  59. * @var \Drupal\Core\File\FileSystemInterface
  60. */
  61. protected $fileSystem;
  62. /**
  63. * Constructs a GDToolkit object.
  64. *
  65. * @param array $configuration
  66. * A configuration array containing information about the plugin instance.
  67. * @param string $plugin_id
  68. * The plugin_id for the plugin instance.
  69. * @param array $plugin_definition
  70. * The plugin implementation definition.
  71. * @param \Drupal\Core\ImageToolkit\ImageToolkitOperationManagerInterface $operation_manager
  72. * The toolkit operation manager.
  73. * @param \Psr\Log\LoggerInterface $logger
  74. * A logger instance.
  75. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
  76. * The config factory.
  77. * @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
  78. * The StreamWrapper manager.
  79. * @param \Drupal\Core\File\FileSystemInterface $file_system
  80. * The file system.
  81. */
  82. public function __construct(array $configuration, $plugin_id, array $plugin_definition, ImageToolkitOperationManagerInterface $operation_manager, LoggerInterface $logger, ConfigFactoryInterface $config_factory, StreamWrapperManagerInterface $stream_wrapper_manager, FileSystemInterface $file_system = NULL) {
  83. parent::__construct($configuration, $plugin_id, $plugin_definition, $operation_manager, $logger, $config_factory);
  84. $this->streamWrapperManager = $stream_wrapper_manager;
  85. if (!$file_system) {
  86. @trigger_error('The file_system service must be passed to GDToolkit::__construct(), it is required before Drupal 9.0.0. See https://www.drupal.org/node/3006851.', E_USER_DEPRECATED);
  87. $file_system = \Drupal::service('file_system');
  88. }
  89. $this->fileSystem = $file_system;
  90. }
  91. /**
  92. * Destructs a GDToolkit object.
  93. *
  94. * Frees memory associated with a GD image resource.
  95. */
  96. public function __destruct() {
  97. if (is_resource($this->resource)) {
  98. imagedestroy($this->resource);
  99. }
  100. }
  101. /**
  102. * {@inheritdoc}
  103. */
  104. public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  105. return new static(
  106. $configuration,
  107. $plugin_id,
  108. $plugin_definition,
  109. $container->get('image.toolkit.operation.manager'),
  110. $container->get('logger.channel.image'),
  111. $container->get('config.factory'),
  112. $container->get('stream_wrapper_manager'),
  113. $container->get('file_system')
  114. );
  115. }
  116. /**
  117. * Sets the GD image resource.
  118. *
  119. * @param resource $resource
  120. * The GD image resource.
  121. *
  122. * @return $this
  123. * An instance of the current toolkit object.
  124. */
  125. public function setResource($resource) {
  126. if (!is_resource($resource) || get_resource_type($resource) != 'gd') {
  127. throw new \InvalidArgumentException('Invalid resource argument');
  128. }
  129. $this->preLoadInfo = NULL;
  130. $this->resource = $resource;
  131. return $this;
  132. }
  133. /**
  134. * Retrieves the GD image resource.
  135. *
  136. * @return resource|null
  137. * The GD image resource, or NULL if not available.
  138. */
  139. public function getResource() {
  140. if (!is_resource($this->resource)) {
  141. $this->load();
  142. }
  143. return $this->resource;
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
  149. $form['image_jpeg_quality'] = [
  150. '#type' => 'number',
  151. '#title' => t('JPEG quality'),
  152. '#description' => t('Define the image quality for JPEG manipulations. Ranges from 0 to 100. Higher values mean better image quality but bigger files.'),
  153. '#min' => 0,
  154. '#max' => 100,
  155. '#default_value' => $this->configFactory->getEditable('system.image.gd')->get('jpeg_quality', FALSE),
  156. '#field_suffix' => t('%'),
  157. ];
  158. return $form;
  159. }
  160. /**
  161. * {@inheritdoc}
  162. */
  163. public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
  164. $this->configFactory->getEditable('system.image.gd')
  165. ->set('jpeg_quality', $form_state->getValue(['gd', 'image_jpeg_quality']))
  166. ->save();
  167. }
  168. /**
  169. * Loads a GD resource from a file.
  170. *
  171. * @return bool
  172. * TRUE or FALSE, based on success.
  173. */
  174. protected function load() {
  175. // Return immediately if the image file is not valid.
  176. if (!$this->isValid()) {
  177. return FALSE;
  178. }
  179. $function = 'imagecreatefrom' . image_type_to_extension($this->getType(), FALSE);
  180. if (function_exists($function) && $resource = $function($this->getSource())) {
  181. $this->setResource($resource);
  182. if (imageistruecolor($resource)) {
  183. return TRUE;
  184. }
  185. else {
  186. // Convert indexed images to truecolor, copying the image to a new
  187. // truecolor resource, so that filters work correctly and don't result
  188. // in unnecessary dither.
  189. $data = [
  190. 'width' => imagesx($resource),
  191. 'height' => imagesy($resource),
  192. 'extension' => image_type_to_extension($this->getType(), FALSE),
  193. 'transparent_color' => $this->getTransparentColor(),
  194. 'is_temp' => TRUE,
  195. ];
  196. if ($this->apply('create_new', $data)) {
  197. imagecopy($this->getResource(), $resource, 0, 0, 0, 0, imagesx($resource), imagesy($resource));
  198. imagedestroy($resource);
  199. }
  200. }
  201. return (bool) $this->getResource();
  202. }
  203. return FALSE;
  204. }
  205. /**
  206. * {@inheritdoc}
  207. */
  208. public function isValid() {
  209. return ((bool) $this->preLoadInfo || (bool) $this->resource);
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. public function save($destination) {
  215. $scheme = StreamWrapperManager::getScheme($destination);
  216. // Work around lack of stream wrapper support in imagejpeg() and imagepng().
  217. if ($scheme && $this->streamWrapperManager->isValidScheme($scheme)) {
  218. // If destination is not local, save image to temporary local file.
  219. $local_wrappers = $this->streamWrapperManager->getWrappers(StreamWrapperInterface::LOCAL);
  220. if (!isset($local_wrappers[$scheme])) {
  221. $permanent_destination = $destination;
  222. $destination = $this->fileSystem->tempnam('temporary://', 'gd_');
  223. }
  224. // Convert stream wrapper URI to normal path.
  225. $destination = $this->fileSystem->realpath($destination);
  226. }
  227. $function = 'image' . image_type_to_extension($this->getType(), FALSE);
  228. if (!function_exists($function)) {
  229. return FALSE;
  230. }
  231. if ($this->getType() == IMAGETYPE_JPEG) {
  232. $success = $function($this->getResource(), $destination, $this->configFactory->get('system.image.gd')->get('jpeg_quality'));
  233. }
  234. else {
  235. // Always save PNG images with full transparency.
  236. if ($this->getType() == IMAGETYPE_PNG) {
  237. imagealphablending($this->getResource(), FALSE);
  238. imagesavealpha($this->getResource(), TRUE);
  239. }
  240. $success = $function($this->getResource(), $destination);
  241. }
  242. // Move temporary local file to remote destination.
  243. if (isset($permanent_destination) && $success) {
  244. try {
  245. $this->fileSystem->move($destination, $permanent_destination, FileSystemInterface::EXISTS_REPLACE);
  246. return TRUE;
  247. }
  248. catch (FileException $e) {
  249. return FALSE;
  250. }
  251. }
  252. return $success;
  253. }
  254. /**
  255. * {@inheritdoc}
  256. */
  257. public function parseFile() {
  258. $data = @getimagesize($this->getSource());
  259. if ($data && in_array($data[2], static::supportedTypes())) {
  260. $this->setType($data[2]);
  261. $this->preLoadInfo = $data;
  262. return TRUE;
  263. }
  264. return FALSE;
  265. }
  266. /**
  267. * Gets the color set for transparency in GIF images.
  268. *
  269. * @return string|null
  270. * A color string like '#rrggbb', or NULL if not set or not relevant.
  271. */
  272. public function getTransparentColor() {
  273. if (!$this->getResource() || $this->getType() != IMAGETYPE_GIF) {
  274. return NULL;
  275. }
  276. // Find out if a transparent color is set, will return -1 if no
  277. // transparent color has been defined in the image.
  278. $transparent = imagecolortransparent($this->getResource());
  279. if ($transparent >= 0) {
  280. // Find out the number of colors in the image palette. It will be 0 for
  281. // truecolor images.
  282. $palette_size = imagecolorstotal($this->getResource());
  283. if ($palette_size == 0 || $transparent < $palette_size) {
  284. // Return the transparent color, either if it is a truecolor image
  285. // or if the transparent color is part of the palette.
  286. // Since the index of the transparent color is a property of the
  287. // image rather than of the palette, it is possible that an image
  288. // could be created with this index set outside the palette size.
  289. // (see http://stackoverflow.com/a/3898007).
  290. $rgb = imagecolorsforindex($this->getResource(), $transparent);
  291. unset($rgb['alpha']);
  292. return Color::rgbToHex($rgb);
  293. }
  294. }
  295. return NULL;
  296. }
  297. /**
  298. * {@inheritdoc}
  299. */
  300. public function getWidth() {
  301. if ($this->preLoadInfo) {
  302. return $this->preLoadInfo[0];
  303. }
  304. elseif ($res = $this->getResource()) {
  305. return imagesx($res);
  306. }
  307. else {
  308. return NULL;
  309. }
  310. }
  311. /**
  312. * {@inheritdoc}
  313. */
  314. public function getHeight() {
  315. if ($this->preLoadInfo) {
  316. return $this->preLoadInfo[1];
  317. }
  318. elseif ($res = $this->getResource()) {
  319. return imagesy($res);
  320. }
  321. else {
  322. return NULL;
  323. }
  324. }
  325. /**
  326. * Gets the PHP type of the image.
  327. *
  328. * @return int
  329. * The image type represented by a PHP IMAGETYPE_* constant (e.g.
  330. * IMAGETYPE_JPEG).
  331. */
  332. public function getType() {
  333. return $this->type;
  334. }
  335. /**
  336. * Sets the PHP type of the image.
  337. *
  338. * @param int $type
  339. * The image type represented by a PHP IMAGETYPE_* constant (e.g.
  340. * IMAGETYPE_JPEG).
  341. *
  342. * @return $this
  343. */
  344. public function setType($type) {
  345. if (in_array($type, static::supportedTypes())) {
  346. $this->type = $type;
  347. }
  348. return $this;
  349. }
  350. /**
  351. * {@inheritdoc}
  352. */
  353. public function getMimeType() {
  354. return $this->getType() ? image_type_to_mime_type($this->getType()) : '';
  355. }
  356. /**
  357. * {@inheritdoc}
  358. */
  359. public function getRequirements() {
  360. $requirements = [];
  361. $info = gd_info();
  362. $requirements['version'] = [
  363. 'title' => t('GD library'),
  364. 'value' => $info['GD Version'],
  365. ];
  366. // Check for filter and rotate support.
  367. if (!function_exists('imagefilter') || !function_exists('imagerotate')) {
  368. $requirements['version']['severity'] = REQUIREMENT_WARNING;
  369. $requirements['version']['description'] = t('The GD Library for PHP is enabled, but was compiled without support for functions used by the rotate and desaturate effects. It was probably compiled using the official GD libraries from http://www.libgd.org instead of the GD library bundled with PHP. You should recompile PHP --with-gd using the bundled GD library. See <a href="http://php.net/manual/book.image.php">the PHP manual</a>.');
  370. }
  371. return $requirements;
  372. }
  373. /**
  374. * {@inheritdoc}
  375. */
  376. public static function isAvailable() {
  377. // GD2 support is available.
  378. return function_exists('imagegd2');
  379. }
  380. /**
  381. * {@inheritdoc}
  382. */
  383. public static function getSupportedExtensions() {
  384. $extensions = [];
  385. foreach (static::supportedTypes() as $image_type) {
  386. // @todo Automatically fetch possible extensions for each mime type.
  387. // @see https://www.drupal.org/node/2311679
  388. $extension = mb_strtolower(image_type_to_extension($image_type, FALSE));
  389. $extensions[] = $extension;
  390. // Add some known similar extensions.
  391. if ($extension === 'jpeg') {
  392. $extensions[] = 'jpg';
  393. $extensions[] = 'jpe';
  394. }
  395. }
  396. return $extensions;
  397. }
  398. /**
  399. * Returns the IMAGETYPE_xxx constant for the given extension.
  400. *
  401. * This is the reverse of the image_type_to_extension() function.
  402. *
  403. * @param string $extension
  404. * The extension to get the IMAGETYPE_xxx constant for.
  405. *
  406. * @return int
  407. * The IMAGETYPE_xxx constant for the given extension, or IMAGETYPE_UNKNOWN
  408. * for unsupported extensions.
  409. *
  410. * @see image_type_to_extension()
  411. */
  412. public function extensionToImageType($extension) {
  413. if (in_array($extension, ['jpe', 'jpg'])) {
  414. $extension = 'jpeg';
  415. }
  416. foreach ($this->supportedTypes() as $type) {
  417. if (image_type_to_extension($type, FALSE) === $extension) {
  418. return $type;
  419. }
  420. }
  421. return IMAGETYPE_UNKNOWN;
  422. }
  423. /**
  424. * Returns a list of image types supported by the toolkit.
  425. *
  426. * @return array
  427. * An array of available image types. An image type is represented by a PHP
  428. * IMAGETYPE_* constant (e.g. IMAGETYPE_JPEG, IMAGETYPE_PNG, etc.).
  429. */
  430. protected static function supportedTypes() {
  431. return [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF];
  432. }
  433. }