[Java]產生SVG向量圖形檔-xml圖形檔
SVG圖檔是一種利用xml及css來製作而成的一種向量圖形,放大或縮小均不會改變其品質,不過當圖形複雜到一定程式時,其檔案也會跟著變大很多,能夠設計SVG圖形作品的軟體工具包括Adobe Illustrator以及CorelDRAW等,要能查看svg檔案裡的圖形可以利用browser像是firefox、chrome都可以直接知道此向量圖形的內容。
在Java要輸出(產生)SVG檔很簡單,在Apache 套件裡有一個batik可以很簡單的就生成所要的SVG圖檔,只需要把原本在建立圖檔時使用的java.awt.Graphics2D變成使用org.apache.batik.svggen.SVGGraphics2D來繪製圖形就可以了。
產生的結果圖:

這個程式是在畫一個紅色範圍區塊,及draw一個字串在圖上。
在開發前需要把所有的batik套件全都載入classpath裡才可以使用,載點
下載後解開檔案,在目錄lib裡,把batik-dom.jar、batik-svggen.jar、batik-awt-util.jar、batik-util.jar、batik-ext.jar、batik.xml.jar載入就可以了

範例程式原始碼下如:
package yku; import java.awt.Color; import java.awt.Graphics2D; import java.io.*; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; public class ImgToSVG { public static void main(String args[]) { DOMImplementation domImpl = GenericDOMImplementation .getDOMImplementation(); // Create an instance of org.w3c.dom.Document. String svgNS = "http://www.w3.org/2000/svg"; Document document = domImpl.createDocument(svgNS, "svg", null); // Create an instance of the SVG Generator. SVGGraphics2D svgGenerator = new SVGGraphics2D(document); // 在背景上畫一個紅色背景 svgGenerator.setPaint(Color.red); svgGenerator.fill(new java.awt.Rectangle(10, 10, 100, 100)); try { String testString = "中文字中文字中文字"; // createGraphics Graphics2D g = svgGenerator; // 設定字型顏色 => BLACK g.setColor(Color.BLACK); // 把文字draw到圖片上 g.drawString(testString, 30, 30); g.dispose(); // 設定 產生檔案路徑 String FilePath = "d:\\TestQRCode.svg"; File f = new File(FilePath); boolean useCSS = true; // we want to use CSS style attributes Writer out = new OutputStreamWriter( new java.io.FileOutputStream(f), "UTF-8"); // 產生SVG檔案 svgGenerator.stream(out, useCSS); } // end try catch (Exception e) { e.printStackTrace(); } // end catch } }
如果用記事本打開產生的svg檔案,可以看到它xml定義的方式

程式下載
留下您想說的話: