如何从SVG获取缓冲图像?
我正在使用蜡染来处理SVG图像。有没有办法从SVG文件中获取java.awt.image.BufferedImage?
我知道有转码器,通过它,我可以将SVG转码为PNG,然后用ImageIO.read()加载该PNG。但我不想有临时文件。
我正在使用蜡染来处理SVG图像。有没有办法从SVG文件中获取java.awt.image.BufferedImage?
我知道有转码器,通过它,我可以将SVG转码为PNG,然后用ImageIO.read()加载该PNG。但我不想有临时文件。
使用蜡染,如下所示:
public static BufferedImage rasterize(File svgFile) throws IOException {
final BufferedImage[] imagePointer = new BufferedImage[1];
// Rendering hints can't be set programatically, so
// we override defaults with a temporary stylesheet.
// These defaults emphasize quality and precision, and
// are more similar to the defaults of other SVG viewers.
// SVG documents can still override these defaults.
String css = "svg {" +
"shape-rendering: geometricPrecision;" +
"text-rendering: geometricPrecision;" +
"color-rendering: optimizeQuality;" +
"image-rendering: optimizeQuality;" +
"}";
File cssFile = File.createTempFile("batik-default-override-", ".css");
FileUtils.writeStringToFile(cssFile, css);
TranscodingHints transcoderHints = new TranscodingHints();
transcoderHints.put(ImageTranscoder.KEY_XML_PARSER_VALIDATING, Boolean.FALSE);
transcoderHints.put(ImageTranscoder.KEY_DOM_IMPLEMENTATION,
SVGDOMImplementation.getDOMImplementation());
transcoderHints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI,
SVGConstants.SVG_NAMESPACE_URI);
transcoderHints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT, "svg");
transcoderHints.put(ImageTranscoder.KEY_USER_STYLESHEET_URI, cssFile.toURI().toString());
try {
TranscoderInput input = new TranscoderInput(new FileInputStream(svgFile));
ImageTranscoder t = new ImageTranscoder() {
@Override
public BufferedImage createImage(int w, int h) {
return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
}
@Override
public void writeImage(BufferedImage image, TranscoderOutput out)
throws TranscoderException {
imagePointer[0] = image;
}
};
t.setTranscodingHints(transcoderHints);
t.transcode(input, null);
}
catch (TranscoderException ex) {
// Requires Java 6
ex.printStackTrace();
throw new IOException("Couldn't convert " + svgFile);
}
finally {
cssFile.delete();
}
return imagePointer[0];
}
一个非常简单的方法是使用 TwelveMonkeys 库,它为 java 的添加了额外的图像类型支持ImageIO
例如,您只需将这些添加到您的专家中(或复制所需的jar):
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-batik</artifactId> <!-- svg -->
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>batik</groupId>
<artifactId>batik-transcoder</artifactId>
<version>1.6-1</version>
</dependency>
然后你只需阅读它
BufferedImage image = ImageIO.read(svg-file);
要检查svg阅读器是否正确注册,您可以打印出图像阅读器:
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("SVG");
while (readers.hasNext()) {
System.out.println("reader: " + readers.next());
}
该库还支持其他参数,请参阅github上的自述文件。