How can I define width/height of svg-sprite and write these values to the file (with Linux or Mac CLI)

287 Views Asked by At

I'm trying to create svg-sprite using npm package svg-sprite. Eventually I get sprite, that looks like this:

// icons-test.svg
...
<svg viewBox="0 0 108 54" ...>
  <svg height="54" width="54" viewBox="-2 -2 54 54" ...>
    <path d="...”>
   </svg>
  <svg height="54" width="54" viewBox="-2 -2 54 54" ...>
    <path d="...”>
  </svg>
</svg>

To define size (for example width) of this svg-sprite I use command identify from util ImageMagick.

identify -format '%w' icons-test.svg

or write it to the file

echo "\$spriteWidth = $(identify -format ‘%w’ icons-test.svg)px" >> styles.styl

The problem is that in file I don't get width of full svg-sprite (108), but only width of last sub-svg image(54), that is included in common svg-sprite.

Please, tell me where is my mistake? How to make identify return correct width. Or advice me another variants to solve the problem.

1

There are 1 best solutions below

2
emcconville On BEST ANSWER

I would suspect that the nested svg tags are confusing ImageMagick's internal SVG decoder. Try converting the SVG into MVG. It should throw-out the nested SVG structure.

$ convert icons-test.svg mvg:-

Which will print the following MVG instructions.

push graphic-context
viewbox 0 0 108 54
affine 1 0 0 1 0 0
push graphic-context
viewbox 0 0 54 54
affine 1 0 0 1 2 2
push graphic-context
path ''
pop graphic-context
pop graphic-context
push graphic-context
viewbox 0 0 54 54
affine 1 0 0 1 2 2
push graphic-context
path ''
pop graphic-context
pop graphic-context
pop graphic-context

With the nested viewboxs isolated to graphic-contexts on the stack, you should be able to identify correctly.

$ convert icons-test.svg mvg:- | identify -format '%w' mvg:-
#=> 108