pom依赖:
<!-- https://mvnrepository.com/artifact/org.apache.xmlgraphics/batik-all -->
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-all</artifactId>
<version>1.10</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-transcoder</artifactId>
<version>1.14</version>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-codec</artifactId>
<version>1.14</version>
</dependency>
代码;
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;
import java.io.*;
/**
* @Author y
* @Date
* @Version 1.0
*/
public 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();
}
}
}
}
public static void main