Java端使用Batik将SVG转为PNG

在上篇中,我们需要将Highcharts生成的图通过后台保存到pdf文件中,就需要对SVG进行转换。
这里就介绍一下使用Batik处理SVG代码的方法。
首先是jar包的获取地址,https://xmlgraphics.apache.org/batik/,Apache旗下的,用起来也比较放心。

需要导入项目的jar包有4个

batik-all-1.11.jar
xml-apis-1.3.04.jar
xml-apis-ext-1.3.04.jar
xmlgraphics-commons-2.3.jar

具体的转换方法如以下代码,直接复制就可以使用

package jp.co.token.emobile.common;

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.ImageTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;

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

    /**
     * 将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);
            // 增加图片的属性设置(单位是像素)---下面是写死了,实际应该是根据SVG的大小动态设置,默认宽高都是400
            t.addTranscodingHint(ImageTranscoder.KEY_WIDTH, new Float(400));
            t.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, new Float(300));
            t.transcode(input, output);
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/ghq120/p/11666942.html