3 namespace Drupal\system\Plugin\ImageToolkit;
5 use Drupal\Component\Utility\Color;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Config\ConfigFactoryInterface;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\Core\ImageToolkit\ImageToolkitBase;
10 use Drupal\Core\ImageToolkit\ImageToolkitOperationManagerInterface;
11 use Drupal\Core\StreamWrapper\StreamWrapperInterface;
12 use Drupal\Core\StreamWrapper\StreamWrapperManagerInterface;
13 use Psr\Log\LoggerInterface;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
17 * Defines the GD2 toolkit for image manipulation within Drupal.
21 * title = @Translation("GD2 image manipulation toolkit")
24 class GDToolkit extends ImageToolkitBase {
27 * A GD image resource.
31 protected $resource = NULL;
34 * Image type represented by a PHP IMAGETYPE_* constant (e.g. IMAGETYPE_JPEG).
41 * Image information from a file, available prior to loading the GD resource.
43 * This contains a copy of the array returned by executing getimagesize()
44 * on the image file when the image object is instantiated. It gets reset
45 * to NULL as soon as the GD resource is loaded.
49 * @see \Drupal\system\Plugin\ImageToolkit\GDToolkit::parseFile()
50 * @see \Drupal\system\Plugin\ImageToolkit\GDToolkit::setResource()
51 * @see http://php.net/manual/function.getimagesize.php
53 protected $preLoadInfo = NULL;
56 * The StreamWrapper manager.
58 * @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
60 protected $streamWrapperManager;
63 * Constructs a GDToolkit object.
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
75 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
77 * @param \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager
78 * The StreamWrapper manager.
80 public function __construct(array $configuration, $plugin_id, array $plugin_definition, ImageToolkitOperationManagerInterface $operation_manager, LoggerInterface $logger, ConfigFactoryInterface $config_factory, StreamWrapperManagerInterface $stream_wrapper_manager) {
81 parent::__construct($configuration, $plugin_id, $plugin_definition, $operation_manager, $logger, $config_factory);
82 $this->streamWrapperManager = $stream_wrapper_manager;
86 * Destructs a GDToolkit object.
88 * Frees memory associated with a GD image resource.
90 public function __destruct() {
91 if (is_resource($this->resource)) {
92 imagedestroy($this->resource);
99 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
104 $container->get('image.toolkit.operation.manager'),
105 $container->get('logger.channel.image'),
106 $container->get('config.factory'),
107 $container->get('stream_wrapper_manager')
112 * Sets the GD image resource.
114 * @param resource $resource
115 * The GD image resource.
117 * @return \Drupal\system\Plugin\ImageToolkit\GDToolkit
118 * An instance of the current toolkit object.
120 public function setResource($resource) {
121 if (!is_resource($resource) || get_resource_type($resource) != 'gd') {
122 throw new \InvalidArgumentException('Invalid resource argument');
124 $this->preLoadInfo = NULL;
125 $this->resource = $resource;
130 * Retrieves the GD image resource.
132 * @return resource|null
133 * The GD image resource, or NULL if not available.
135 public function getResource() {
136 if (!is_resource($this->resource)) {
139 return $this->resource;
145 public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
146 $form['image_jpeg_quality'] = [
148 '#title' => t('JPEG quality'),
149 '#description' => t('Define the image quality for JPEG manipulations. Ranges from 0 to 100. Higher values mean better image quality but bigger files.'),
152 '#default_value' => $this->configFactory->getEditable('system.image.gd')->get('jpeg_quality', FALSE),
153 '#field_suffix' => t('%'),
161 public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
162 $this->configFactory->getEditable('system.image.gd')
163 ->set('jpeg_quality', $form_state->getValue(['gd', 'image_jpeg_quality']))
168 * Loads a GD resource from a file.
171 * TRUE or FALSE, based on success.
173 protected function load() {
174 // Return immediately if the image file is not valid.
175 if (!$this->isValid()) {
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)) {
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.
190 'width' => imagesx($resource),
191 'height' => imagesy($resource),
192 'extension' => image_type_to_extension($this->getType(), FALSE),
193 'transparent_color' => $this->getTransparentColor(),
196 if ($this->apply('create_new', $data)) {
197 imagecopy($this->getResource(), $resource, 0, 0, 0, 0, imagesx($resource), imagesy($resource));
198 imagedestroy($resource);
201 return (bool) $this->getResource();
209 public function isValid() {
210 return ((bool) $this->preLoadInfo || (bool) $this->resource);
216 public function save($destination) {
217 $scheme = file_uri_scheme($destination);
218 // Work around lack of stream wrapper support in imagejpeg() and imagepng().
219 if ($scheme && file_stream_wrapper_valid_scheme($scheme)) {
220 // If destination is not local, save image to temporary local file.
221 $local_wrappers = $this->streamWrapperManager->getWrappers(StreamWrapperInterface::LOCAL);
222 if (!isset($local_wrappers[$scheme])) {
223 $permanent_destination = $destination;
224 $destination = drupal_tempnam('temporary://', 'gd_');
226 // Convert stream wrapper URI to normal path.
227 $destination = \Drupal::service('file_system')->realpath($destination);
230 $function = 'image' . image_type_to_extension($this->getType(), FALSE);
231 if (!function_exists($function)) {
234 if ($this->getType() == IMAGETYPE_JPEG) {
235 $success = $function($this->getResource(), $destination, $this->configFactory->get('system.image.gd')->get('jpeg_quality'));
238 // Always save PNG images with full transparency.
239 if ($this->getType() == IMAGETYPE_PNG) {
240 imagealphablending($this->getResource(), FALSE);
241 imagesavealpha($this->getResource(), TRUE);
243 $success = $function($this->getResource(), $destination);
245 // Move temporary local file to remote destination.
246 if (isset($permanent_destination) && $success) {
247 return (bool) file_unmanaged_move($destination, $permanent_destination, FILE_EXISTS_REPLACE);
255 public function parseFile() {
256 $data = @getimagesize($this->getSource());
257 if ($data && in_array($data[2], static::supportedTypes())) {
258 $this->setType($data[2]);
259 $this->preLoadInfo = $data;
266 * Gets the color set for transparency in GIF images.
268 * @return string|null
269 * A color string like '#rrggbb', or NULL if not set or not relevant.
271 public function getTransparentColor() {
272 if (!$this->getResource() || $this->getType() != IMAGETYPE_GIF) {
275 // Find out if a transparent color is set, will return -1 if no
276 // transparent color has been defined in the image.
277 $transparent = imagecolortransparent($this->getResource());
278 if ($transparent >= 0) {
279 // Find out the number of colors in the image palette. It will be 0 for
281 $palette_size = imagecolorstotal($this->getResource());
282 if ($palette_size == 0 || $transparent < $palette_size) {
283 // Return the transparent color, either if it is a truecolor image
284 // or if the transparent color is part of the palette.
285 // Since the index of the transparent color is a property of the
286 // image rather than of the palette, it is possible that an image
287 // could be created with this index set outside the palette size.
288 // (see http://stackoverflow.com/a/3898007).
289 $rgb = imagecolorsforindex($this->getResource(), $transparent);
290 unset($rgb['alpha']);
291 return Color::rgbToHex($rgb);
300 public function getWidth() {
301 if ($this->preLoadInfo) {
302 return $this->preLoadInfo[0];
304 elseif ($res = $this->getResource()) {
305 return imagesx($res);
315 public function getHeight() {
316 if ($this->preLoadInfo) {
317 return $this->preLoadInfo[1];
319 elseif ($res = $this->getResource()) {
320 return imagesy($res);
328 * Gets the PHP type of the image.
331 * The image type represented by a PHP IMAGETYPE_* constant (e.g.
334 public function getType() {
339 * Sets the PHP type of the image.
342 * The image type represented by a PHP IMAGETYPE_* constant (e.g.
347 public function setType($type) {
348 if (in_array($type, static::supportedTypes())) {
357 public function getMimeType() {
358 return $this->getType() ? image_type_to_mime_type($this->getType()) : '';
364 public function getRequirements() {
368 $requirements['version'] = [
369 'title' => t('GD library'),
370 'value' => $info['GD Version'],
373 // Check for filter and rotate support.
374 if (!function_exists('imagefilter') || !function_exists('imagerotate')) {
375 $requirements['version']['severity'] = REQUIREMENT_WARNING;
376 $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>.');
379 return $requirements;
385 public static function isAvailable() {
386 // GD2 support is available.
387 return function_exists('imagegd2');
393 public static function getSupportedExtensions() {
395 foreach (static::supportedTypes() as $image_type) {
396 // @todo Automatically fetch possible extensions for each mime type.
397 // @see https://www.drupal.org/node/2311679
398 $extension = Unicode::strtolower(image_type_to_extension($image_type, FALSE));
399 $extensions[] = $extension;
400 // Add some known similar extensions.
401 if ($extension === 'jpeg') {
402 $extensions[] = 'jpg';
403 $extensions[] = 'jpe';
410 * Returns the IMAGETYPE_xxx constant for the given extension.
412 * This is the reverse of the image_type_to_extension() function.
414 * @param string $extension
415 * The extension to get the IMAGETYPE_xxx constant for.
418 * The IMAGETYPE_xxx constant for the given extension, or IMAGETYPE_UNKNOWN
419 * for unsupported extensions.
421 * @see image_type_to_extension()
423 public function extensionToImageType($extension) {
424 if (in_array($extension, ['jpe', 'jpg'])) {
427 foreach ($this->supportedTypes() as $type) {
428 if (image_type_to_extension($type, FALSE) === $extension) {
432 return IMAGETYPE_UNKNOWN;
436 * Returns a list of image types supported by the toolkit.
439 * An array of available image types. An image type is represented by a PHP
440 * IMAGETYPE_* constant (e.g. IMAGETYPE_JPEG, IMAGETYPE_PNG, etc.).
442 protected static function supportedTypes() {
443 return [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF];