annotate core/modules/system/src/Plugin/ImageToolkit/GDToolkit.php @ 19:fa3358dc1485 tip

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