1 image.inc | image_get_svg_dimensions($uri) |
Get an SVG image's defined dimensions.
@since 1.28.0 Function added.
Parameters
string $uri: The URI or path to an SVG image.
Return value
array|FALSE: An array containing the keys "width" and "height" as integer values. If the image is an SVG but no set dimensions are available, these keys will have NULL values. If the image is not an SVG, or the SVG file is empty or invalid, FALSE will be returned.
Related topics
File
- core/
includes/ image.inc, line 642 - API for manipulating images.
Code
function image_get_svg_dimensions($uri) {
// Safety check.
if (!image_is_svg($uri)) {
return FALSE;
}
// Return cached dimensions if already retrieved once this request.
$cached_images = &backdrop_static(__FUNCTION__, array());
if (isset($cached_images[$uri])) {
return $cached_images[$uri];
}
// If there are no dimensions, store the dimensions as zero.
// Required for compatibility with image field storage.
$svg_dimensions = array();
$file_contents = file_get_contents($uri);
if ($file_contents && $svg = simplexml_load_string($file_contents)) {
foreach ($svg->attributes() as $attribute => $value) {
if ($attribute === 'width' || $attribute === 'height') {
$svg_dimensions[$attribute] = (int) $value;
}
}
}
else {
return FALSE;
}
// Save values to static cache.
$cached_images[$uri] = $svg_dimensions;
return $svg_dimensions;
}