Skip to content
Snippets Groups Projects
Commit cf12fa39 authored by Ivica Puljic's avatar Ivica Puljic
Browse files

Issue #3389133 by pivica: Add service for extraction dimensions from SVG image

parent 0c88bbe1
No related branches found
No related tags found
No related merge requests found
services:
bs_lib.svg_tools:
class: Drupal\bs_lib\SvgTools
<?php
namespace Drupal\bs_lib;
/**
* Defines a service with some handy SVG tools.
*/
class SvgTools {
/**
* Extracts width and height dimensions from an SVG content string.
*
* This function attempts to retrieve the width and height attributes from the
* SVG content. If these attributes are not found, it falls back to extracting
* the dimensions from the viewBox attribute. The extracted dimensions are
* returned as an associative array with 'width' and 'height' keys.
*
* @param string $svg_content
* The SVG content to extract dimensions from.
*
* @return array|false
* An associative array containing 'width' and 'height' dimensions, or FALSE
* if width or height are not found.
*/
public function getDimensions(string $svg_content)
{
$width = NULL;
$height = NULL;
// First try to get dimensions from width and height attribute.
preg_match('/<svg[^>]*width=["\']?([^"\']+)["\']?[^>]*>/i', $svg_content, $widthMatches);
if (!empty($widthMatches[1])) {
$width = $widthMatches[1];
}
preg_match('/<svg[^>]*height=["\']?([^"\']+)["\']?[^>]*>/i', $svg_content, $heightMatches);
if (!empty($heightMatches[1])) {
$height = $heightMatches[1];
}
// If width or height attributes were not found, try to extract from
// viewBox attribute.
if (!$width || !$height) {
preg_match('/<svg[^>]*viewBox=["\']?([^"\']+)["\']?[^>]*>/i', $svg_content, $viewBoxMatches);
if (!empty($viewBoxMatches[1])) {
$viewBoxValues = explode(' ', $viewBoxMatches[1]);
if (count($viewBoxValues) >= 4) {
$width = $viewBoxValues[2];
$height = $viewBoxValues[3];
}
}
}
if (!empty($width) && !empty($height)) {
return [
'width' => $this->removeUnit($width),
'height' => $this->removeUnit($height),
];
}
return FALSE;
}
/**
* Removes units from a given value and returns the numeric representation.
*
* This method takes a string value as input, removes any non-numeric and
* non-dot characters (excluding the dot to allow floating-point numbers),
* and converts the resulting string to a float.
*
* @param string $value
* The input value, which may include units or be a numeric string.
* @return float
* The numeric representation of the input value without units.
*
*/
protected function removeUnit($value) {
// Remove non-numeric and non-dot characters from the value.
$numericValue = preg_replace('/[^0-9.]/', '', $value);
// Convert the numeric value to a float.
return floatval($numericValue);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment