100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > java batik_Java端使用Batik将SVG转为PNG

java batik_Java端使用Batik将SVG转为PNG

时间:2020-04-20 21:55:10

相关推荐

java batik_Java端使用Batik将SVG转为PNG

在上篇中,我们需要将Highcharts生成的图通过后台保存到pdf文件中,就需要对SVG进行转换。

这里就介绍一下使用Batik处理SVG代码的方法。

首先是jar包的获取地址,/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.mon;

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();

}

}

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。