Thursday, June 18, 2009

groovyでSVGをPNGにレンダリングする

groovyでSVGをPNGにレンダリングするには、以下のコードを実行します。


import java.lang.ref.*
import java.awt.*
import java.awt.image.*
import javax.imageio.*
import org.apache.batik.bridge.*
import org.apache.batik.dom.svg.*
import org.apache.batik.util.*
import org.w3c.dom.svg.*
import org.apache.batik.ext.awt.*;

img = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB)
parser = XMLResourceDescriptor.getXMLParserClassName()
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser)
svgf = new File("./masked-image-dropshadow.svg");
URI furi = svgf.toURI();
svgd = factory.createDocument(furi.toString());
userAgentAdapter = new UserAgentAdapter();
bridgeContext = new BridgeContext(userAgentAdapter);
builder = new GVTBuilder();
rsvgn = builder.build(bridgeContext, svgd)
Graphics2D g2d = img.getGraphics()
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR)
//g2d.getRenderingHints().remove(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE);
g2d.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, new WeakReference(img));
rsvgn.paint(g2d);
g2d.dispose();
ImageIO.write(img, "png", new File("sample993a.png"));


元画像(sf.jpg)


入力SVG(masked-image-dropshadow.svg)

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="300" height="300">

<defs>
<mask id="mask1" maskUnits="userSpaceOnUse"
x="0" y="0" width="300" height="300">
<rect x="50" y="50" width="200" height="200"
rx="20" ry="20"
style="fill:#ffffff; "/>
</mask>
<filter id="gbf">
<feGaussianBlur in="SourceAlpha" stdDeviation="4" result="shadow"/>
<feOffset in="shadow" dx="4" dy="4" result="shadow2"/>
<feComposite in="SourceGraphic" in2="shadow2" operator="over"/>
</filter>
</defs>

<g filter="url(#gbf)">
<image x="50" y="50" width="200px" height="200px"
xlink:href="sf.jpg" mask="url(#mask1)" >
<title>sf.jpg</title>
</image>
</g>
<!--mask="url(#mask1)" -->
</svg>


出力画像(sample993a.png)
groovyでSVGをPNGに変換した画像

No comments: