function svg_image_get_image_file_dimensions in Svg Image 1.x
Same name and namespace in other branches
- 8 svg_image.module \svg_image_get_image_file_dimensions()
- 2.x svg_image.module \svg_image_get_image_file_dimensions()
Provides image file dimensions.
Parameters
\Drupal\file\Entity\File $file: SVG file.
Return value
integer[] Dimensions array.
1 call to svg_image_get_image_file_dimensions()
- SvgImageWidget::process in src/
Plugin/ Field/ FieldWidget/ SvgImageWidget.php - Form API callback: Processes a file_generic field element.
File
- ./
svg_image.module, line 59 - Contains main functions and hooks for svg_image module.
Code
function svg_image_get_image_file_dimensions(File $file) {
$image = \Drupal::getContainer()
->get('image.factory')
->get($file
->getFileUri());
$variables = [];
if ($image
->isValid()) {
$variables['width'] = $image
->getWidth();
$variables['height'] = $image
->getHeight();
}
else {
// Set default width and height values.
$variables['width'] = $variables['height'] = 64;
// We can find out only dimensions of the SVG files.
if (svg_image_is_file_svg($file)) {
// Parse SVG as XML.
$fileContents = file_get_contents($file
->getFileUri());
// In some cases file could be not available for the loading. It could be
// deleted from the files folder physically, moved to other place or
// permissions will not allow to read it. In this case we will just skip
// dimensions discovering.
if ($fileContents) {
$svg = simplexml_load_string($fileContents);
$neededVariables = [
'width',
'height',
];
if ($svg) {
foreach ($svg
->attributes() as $attribute => $value) {
if (in_array($attribute, $neededVariables)) {
$variables[$attribute] = (int) $value;
}
}
}
}
}
}
return $variables;
}