phpsvgdimensions

How do you get the width and height of an SVG picture in PHP?


I tried to use getimagesize() on an SVG file, but it failed.

I know that SVG is “Scalable Vector Graphics”, but I find that Google Chrome’s “Review elements” can perfectly get the dimensions of an SVG picture, so I suspect that this is also possible in PHP.

If it is difficult to get the dimensions, is there any way to judge whether an SVG picture is vertical or horizontal?


Solution

  • The thing is: SVG images don't have a "size" in the sense you are probably thinking of. On the other hand, they DO have a height-to-width ratio.

    This ratio can usually be found in the viewBox attribute.

    If, on the other hand, the viewBox attribute is not present on the root SVG element, the image ratio is highly nontrivial to determine.

    Edit:

    Side note: The reason Chrome gives you perfect coordinates isn't necessarily because it looks at the SVG to determine size; it could very well be a simple result of it setting the size.

    Although the SVG element does have height and width attributes, these might not be specified as pixels, but any of a number of units, so they aren't necessarily a lot of help.