views:

192

answers:

4

Hi, I would like to be able to convert SVG documents to black and white. My try is the following Makefile script using 'sed' :

%.bw.svg: %.svg
    sed '/stroke:none/!s/stroke:[^;\"]*/stroke:black/g' $< > $@

This works for lines etc but not for fillings. Basically if the stroke is not invisible (none), then I convert it to black. I would like to do the same for fillings, if not white or invisible, then convert to black.

I wonder if it would be too complex to do something like this in a better way, perhaps using XSLT, but I have no experience. Anyone can help ?

A: 

My first thought is that it can be dangerous to manipulate XML (in this case SVG) via sed etc. since it won't escape XML chars properly or respect character encodings.

Having said that, your dataset may be sufficiently constrained and limited such that this isn't a particular problem.

Considering XPath solutions (inc. XSLT) sounds good since you'll be able to precisely identify the components you want to change. Some implementation of XQuery may be of use here.

A very different alternative is XMLStarlet - a command line toolset used for processing XML in scripts.

Finally, can you use a programmatic toolset to do this ? Batik would be my first choice (in the Java world).

Brian Agnew
I was thinking of something simple... cant this be done in 10 lines of code?
Helltone
I'm not familiar enough with the problem domain to give that sort of indication
Brian Agnew
A: 

I think you need a full CSS parser to do this job for all of SVG; but for "SVG as generated by some particular vector editing application", XSLT containing string editing of the style attributes (as you're doing now, except that it will properly stick to the styles and avoid e.g. <text>) might be adequate.

It would be useful if you'd edit your question to explain how your strategy fails for fill colors.

Kevin Reid
+1  A: 

Two options that I would try:

1- Inkscape appears to be able to do it - Inkscape Convert
2- SVG supports a ColorProfile attribute on the SVG element that can reference an ICC Color Profile. I would try to reference a GrayScale color profile there and see what happens. Looks like there is one available here.

Jacob G
Helltone
A: 

First of all: Don't try doing this with sed. Editing XML is a little more complex than that.

You can use an SVG filter effect on the image. The ColorMatrix filter primitive can desaturate an image.

Joey