Commit 87c73d8a authored by alexpott's avatar alexpott

Issue #2652138 by phenaproxima, mondrake, nabiyllin, Gravypower, alexpott, Wim...

Issue #2652138 by phenaproxima, mondrake, nabiyllin, Gravypower, alexpott, Wim Leers, claudiu.cristea: Image styles do not play nicely with SVGs
parent 34bf287a
...@@ -292,10 +292,28 @@ function template_preprocess_image_style(&$variables) { ...@@ -292,10 +292,28 @@ function template_preprocess_image_style(&$variables) {
'#width' => $dimensions['width'], '#width' => $dimensions['width'],
'#height' => $dimensions['height'], '#height' => $dimensions['height'],
'#attributes' => $variables['attributes'], '#attributes' => $variables['attributes'],
'#uri' => $style->buildUrl($variables['uri']),
'#style_name' => $variables['style_name'], '#style_name' => $variables['style_name'],
]; ];
// If the current image toolkit supports this file type, prepare the URI for
// the derivative image. If not, just use the original image resized to the
// dimensions specified by the style.
if ($style->supportsUri($variables['uri'])) {
$variables['image']['#uri'] = $style->buildUrl($variables['uri']);
}
else {
$variables['image']['#uri'] = $variables['uri'];
// Don't render the image by default, but allow other preprocess functions
// to override that if they need to.
$variables['image']['#access'] = FALSE;
// Inform the site builders why their image didn't work.
\Drupal::logger('image')->warning('Could not apply @style image style to @uri because the style does not support it.', [
'@style' => $style->label(),
'@uri' => $variables['uri'],
]);
}
if (isset($variables['alt']) || array_key_exists('alt', $variables)) { if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
$variables['image']['#alt'] = $variables['alt']; $variables['image']['#alt'] = $variables['alt'];
} }
......
...@@ -14,9 +14,11 @@ ...@@ -14,9 +14,11 @@
use Drupal\image\ImageStyleInterface; use Drupal\image\ImageStyleInterface;
use Drupal\Component\Utility\Crypt; use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\UrlHelper; use Drupal\Component\Utility\UrlHelper;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\StreamWrapper\StreamWrapperInterface; use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Drupal\Core\Entity\Entity\EntityViewDisplay; use Drupal\Core\Entity\Entity\EntityViewDisplay;
/** /**
* Defines an image style configuration entity. * Defines an image style configuration entity.
* *
...@@ -274,9 +276,8 @@ public function flush($path = NULL) { ...@@ -274,9 +276,8 @@ public function flush($path = NULL) {
* {@inheritdoc} * {@inheritdoc}
*/ */
public function createDerivative($original_uri, $derivative_uri) { public function createDerivative($original_uri, $derivative_uri) {
// If the source file doesn't exist, return FALSE without creating folders. // If the source file doesn't exist, return FALSE without creating folders.
$image = \Drupal::service('image.factory')->get($original_uri); $image = $this->getImageFactory()->get($original_uri);
if (!$image->isValid()) { if (!$image->isValid()) {
return FALSE; return FALSE;
} }
...@@ -340,6 +341,18 @@ public function deleteImageEffect(ImageEffectInterface $effect) { ...@@ -340,6 +341,18 @@ public function deleteImageEffect(ImageEffectInterface $effect) {
return $this; return $this;
} }
/**
* {@inheritdoc}
*/
public function supportsUri($uri) {
// Only support the URI if its extension is supported by the current image
// toolkit.
return in_array(
Unicode::strtolower(pathinfo($uri, PATHINFO_EXTENSION)),
$this->getImageFactory()->getSupportedExtensions()
);
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
...@@ -408,6 +421,16 @@ protected function getImageEffectPluginManager() { ...@@ -408,6 +421,16 @@ protected function getImageEffectPluginManager() {
return \Drupal::service('plugin.manager.image.effect'); return \Drupal::service('plugin.manager.image.effect');
} }
/**
* Returns the image factory.
*
* @return \Drupal\Core\Image\ImageFactory
* The image factory.
*/
protected function getImageFactory() {
return \Drupal::service('image.factory');
}
/** /**
* Gets the Drupal private key. * Gets the Drupal private key.
* *
......
...@@ -194,4 +194,15 @@ public function addImageEffect(array $configuration); ...@@ -194,4 +194,15 @@ public function addImageEffect(array $configuration);
*/ */
public function deleteImageEffect(ImageEffectInterface $effect); public function deleteImageEffect(ImageEffectInterface $effect);
/**
* Determines if this style can be applied to a given image.
*
* @param string $uri
* The URI of the image.
*
* @return bool
* TRUE if the image is supported, FALSE otherwise.
*/
public function supportsUri($uri);
} }
...@@ -7,6 +7,8 @@ ...@@ -7,6 +7,8 @@
use Drupal\entity_test\Entity\EntityTest; use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig; use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig; use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\field\Kernel\FieldKernelTestBase; use Drupal\Tests\field\Kernel\FieldKernelTestBase;
/** /**
...@@ -99,4 +101,89 @@ public function testImageFormatterCacheTags() { ...@@ -99,4 +101,89 @@ public function testImageFormatterCacheTags() {
$this->assertEquals($entity->{$this->fieldName}[1]->entity->getCacheTags(), $build[$this->fieldName][1]['#cache']['tags'], 'Second image cache tags is as expected'); $this->assertEquals($entity->{$this->fieldName}[1]->entity->getCacheTags(), $build[$this->fieldName][1]['#cache']['tags'], 'Second image cache tags is as expected');
} }
/**
* Tests ImageFormatter's handling of SVG images.
*
* @requires extension gd
*/
public function testImageFormatterSvg() {
// Install the default image styles.
$this->installConfig(['image']);
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$png = File::create([
'uri' => 'public://test-image.png',
]);
$png->save();
// We need to create an actual empty PNG, or the GD toolkit will not
// consider the image valid.
$png_resource = imagecreate(300, 300);
imagefill($png_resource, 0, 0, imagecolorallocate($png_resource, 0, 0, 0));
imagepng($png_resource, $png->getFileUri());
$svg = File::create([
'uri' => 'public://test-image.svg',
]);
$svg->save();
// We don't have to put any real SVG data in here, because the GD toolkit
// won't be able to load it anyway.
touch($svg->getFileUri());
$entity = EntityTest::create([
'name' => $this->randomMachineName(),
$this->fieldName => [$png, $svg],
]);
$entity->save();
// Ensure that the display is using the medium image style.
$component = $this->display->getComponent($this->fieldName);
$component['settings']['image_style'] = 'medium';
$this->display->setComponent($this->fieldName, $component)->save();
$build = $this->display->build($entity);
// The first image is a PNG, so it is supported by the GD image toolkit.
// The image style should be applied with its cache tags, image derivative
// computed with its URI and dimensions.
$this->assertCacheTags($build[$this->fieldName][0], ImageStyle::load('medium')->getCacheTags());
$renderer->renderRoot($build[$this->fieldName][0]);
$this->assertEquals('medium', $build[$this->fieldName][0]['#image_style']);
// We check that the image URL contains the expected style directory
// structure.
$this->assertTrue(strpos($build[$this->fieldName][0]['#markup'], 'styles/medium/public/test-image.png') !== FALSE);
$this->assertTrue(strpos($build[$this->fieldName][0]['#markup'], 'width="220"') !== FALSE);
$this->assertTrue(strpos($build[$this->fieldName][0]['#markup'], 'height="220"') !== FALSE);
// The second image is an SVG, which is not supported by the GD toolkit.
// The image style should still be applied with its cache tags, but image
// derivative will not be available so <img> tag will point to the original
// image.
$this->assertCacheTags($build[$this->fieldName][1], ImageStyle::load('medium')->getCacheTags());
$renderer->renderRoot($build[$this->fieldName][1]);
$this->assertEquals('medium', $build[$this->fieldName][1]['#image_style']);
// We check that the image URL does not contain the style directory
// structure.
$this->assertFalse(strpos($build[$this->fieldName][1]['#markup'], 'styles/medium/public/test-image.svg'));
// Since we did not store original image dimensions, width and height
// HTML attributes will not be present.
$this->assertFalse(strpos($build[$this->fieldName][1]['#markup'], 'width'));
$this->assertFalse(strpos($build[$this->fieldName][1]['#markup'], 'height'));
}
/**
* Asserts that a renderable array has a set of cache tags.
*
* @param array $renderable
* The renderable array. Must have a #cache[tags] element.
* @param array $cache_tags
* The expected cache tags.
*/
protected function assertCacheTags(array $renderable, array $cache_tags) {
$diff = array_diff($cache_tags, $renderable['#cache']['tags']);
$this->assertEmpty($diff);
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment