1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.OutputStream;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.FileUtils;
public class SVG2PNG {
/**
* 将指定目录中的svg文件转换成png格式
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
File[] svgs = new File("H:\\tmp\\图标").listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith("svg");
}
});
for (File file : svgs) {
convertToPng(file);
}
}
public static boolean convertToPng(File svgFile) throws Exception {
OutputStream outputStream = null;
try {
String pngName = svgFile.getName().replaceAll("svg$", "png");
outputStream = new FileOutputStream(svgFile.getParent() + "\\" + pngName);
byte[] svg = FileUtils.readFileToByteArray(svgFile);
PNGTranscoder t = new PNGTranscoder();
TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svg));
TranscoderOutput output = new TranscoderOutput(outputStream);
t.transcode(input, output);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (outputStream != null) {
outputStream.close();
}
}
return true;
}
}
|