image-processingsvgimagemagicklibrsvgrsvg

How do you convert an SVG image "paths" into separate PNG images?


I've got an SVG image with 67 separate paths.

Are there any libraries/tutorials out there that will create a separate raster image such as a PNG for each of those paths, and perhaps name them according to the path id?


Solution

  • I don't know of any libraries which would support this exact workflow directly, but that's probably because at least on the surface it seems super trivial. Assuming you're talking about top-level <path/> nodes, then this should be accomplishable with any library that can work with XML - just work with the raw XML directly and ignore the fact that this particular document is SVG. If you have:

    <svg ...>
      <path title="a" d="M 100 100 L 300 100 L 200 300 z" stroke-width="3" />
      <path title="b" d="M 200 100 L 300 100 L 200 300 z" stroke-width="3" />
      <path title="c" d="M 300 100 L 300 100 L 200 300 z" stroke-width="3" />
    </svg>
    

    And you want:

    [a.svg]
    <svg ...>
      <path d="M 100 100 L 300 100 L 200 300 z" stroke="blue" stroke-width="3" />
    </svg>
    
    [b.svg]
    <svg ...>
      <path d="M 200 100 L 300 100 L 200 300 z" stroke="blue" stroke-width="3" />
    </svg>
    

    Then you just need to use your language/library/tool of choice and define the path to the "path" nodes, suck them out of the root document and grab the title attribute, and copy them into a new document which shares the same original canvas attributes (if that is appropriate in your case - or change them into whatever you need) with the title as the file name. This should be pretty trivial with any XML parser and even most basic DOM handling API (or XSLT/XPATH, etc.).