使用Batik绘制SVG图并保存为png图像格式

SVG(Scalable Vector Graph)--可缩放矢量图形.

可缩放矢量图形是基于可扩展标记语言标准通用标记语言的子集),用于描写叙述二维矢量图形的一种图形格式。它由万维网联盟制定。是一个开放标准。


思考

使用SVG实现一个miniCAD

參考代码来源http://outofmemory.cn/code-snippet/1096/java-jiang-svg-tupian-switch-png-format-tupian:

package cn.outofmemory.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;

/**
 * 将svg转换为png格式的图片
 * 
 * 
 */
public abstract class SvgPngConverter {

    /**
     * 将svg字符串转换为png
     * 
     * @param svgCode svg代码
     * @param pngFilePath 保存的路径
     * @throws TranscoderException svg代码异常
     * @throws IOException io错误
     */
    public static void convertToPng(String svgCode, String pngFilePath) throws IOException,
            TranscoderException {

        File file = new File(pngFilePath);

        FileOutputStream outputStream = null;
        try {
            file.createNewFile();
            outputStream = new FileOutputStream(file);
            convertToPng(svgCode, outputStream);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将svgCode转换成png文件。直接输出到流中
     * 
     * @param svgCode svg代码
     * @param outputStream 输出流
     * @throws TranscoderException 异常
     * @throws IOException io异常
     */
    public static void convertToPng(String svgCode, OutputStream outputStream)
            throws TranscoderException, IOException {
        try {
            byte[] bytes = svgCode.getBytes("utf-8");
            PNGTranscoder t = new PNGTranscoder();
            TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
            TranscoderOutput output = new TranscoderOutput(outputStream);
            t.transcode(input, output);
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

编译依赖:

batik-all-1.7.jar  xml-commons-external-1.4.01.jar


拷贝上两个jar到classpath或当前文件夹下,编译自己定义程序:

javac -classpath  batik-all-1.7.jar  XXX.java


程序中调用:convertToPng(tmp_str, outimgfilename);


posted @ 2017-05-08 15:09  yxysuanfa  阅读(1733)  评论(0编辑  收藏  举报