1.替换img地址
/**
* 替换img地址
* @param str -- 前台svg字符串
* @return
*/
private String transferImgPath(HttpServletRequest request,String str) {
System.out.println(str);
String requestURL = request.getRequestURL().toString();
String requestURI = request.getRequestURI();
String httpURL = requestURL.replace(requestURI,"");
String ptn = "(?i)href=\"([^\"]*)\"[^>]*>";
Pattern p = Pattern.compile(ptn, Pattern.DOTALL);
Matcher m = p.matcher(str);
List<String> list = new ArrayList<String>();
while(m.find()) {
String imgurl = m.group(1);
if(!imgurl.contains("http") && !list.contains(imgurl)) {
str = str.replaceAll(imgurl,httpURL + "/resources/myflow-min/" + imgurl);
}
list.add(imgurl);
}
return str;
}2.将svg字符串转换为png
/**
* 将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();
}
}
}
}3.用的jar包
batik-all-1.7.jar
xml-apis-ext.jar
本文介绍了如何在Java后台使用Batik库将SVG图像转换为PNG格式,包括关键步骤和所需依赖库。
1974

被折叠的 条评论
为什么被折叠?



