java将svgxml转png_java后台svg字符串转成png 该篇⽂章只写了将SVG报⽂字符串转PNG,后续再更新SVG图⽚转PNG,如有问题点,请⼤家留⾔,谢谢!⼀、引jar包
需要引⼊的jar包包含如下:(这⾥的jar包版本,⼤家可以根据⾃⼰的maven私服上的版本做对应关系,可以是其他版本号)
lgraphics
batik-all
1.7
xml-apis
xml-apis-ext
1.3.04
lgraphics
batik-codec
1.7
⼆、相关代码
package com.mdp.backend.frame.impl.utils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.anscoder.TranscoderInput;
import org.anscoder.TranscoderOutput;
import org.anscoder.image.PNGTranscoder;
/**
* 流程图⽚操作
* @author lixiaolong
*
*/
public class ProcessPictureUtils {
/**
* 将svg字符串转换为png
*
* @param svgCode svg代码
* @param pngFilePath 保存的路径
* @throws TranscoderException svg代码异常
* @throws IOException io错误
*/
public static String convertToPng(String svgCode, String pngFilePath){
String errorMessage = "";
File file = new File(pngFilePath);
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
convertToPng(svgCode, outputStream);
}catch(Exception e) {
e.printStackTrace();
errorMessage = "将svg字符串转换为png出错!";
Log4jUtils.info(String.format("将svg字符串转换为png出错!: Excepion:=%s",e)); }finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return errorMessage;
}
/**
* 将svgCode转换成png⽂件,直接输出到流中
*
* @param svgCode svg代码
* @param outputStream 输出流
* @throws TranscoderException 异常
svg图* @throws IOException io异常
*/
public static void convertToPng(String svgCode, OutputStream outputStream){ try {
byte[] bytes = Bytes("utf-8");
PNGTranscoder t = new PNGTranscoder();
TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes)); TranscoderOutput output = new TranscoderOutput(outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
Log4jUtils.info(String.format("将svg转换成png⽂件,直接输出到流中出错!: Excepion:=%s",e)); }
}
}三、测试报⽂字符串样例
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n"-//W3C//DTD SVG 1.1//EN\"
\"/Graphics/SVG/1.1/DTD/svg11.dtd\">\n1"四、效果图

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。