如何从SVG获取BufferedImage?

如何从SVG获取BufferedImage?,第1张

如何从SVG获取BufferedImage?

使用蜡染,如下所示:

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 transprerHints = new TranscodingHints();    transprerHints.put(ImageTransprer.KEY_XML_PARSER_VALIDATING, Boolean.FALSE);    transprerHints.put(ImageTransprer.KEY_DOM_IMPLEMENTATION, SVGDOMImplementation.getDOMImplementation());    transprerHints.put(ImageTransprer.KEY_document_ELEMENT_NAMESPACE_URI, SVGConstants.SVG_NAMESPACE_URI);    transprerHints.put(ImageTransprer.KEY_document_ELEMENT, "svg");    transprerHints.put(ImageTransprer.KEY_USER_STYLESHEET_URI, cssFile.toURI().toString());    try {        TransprerInput input = new TransprerInput(new FileInputStream(svgFile));        ImageTransprer t = new ImageTransprer() { @Override public BufferedImage createImage(int w, int h) {     return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); } @Override public void writeImage(BufferedImage image, TransprerOutput out)         throws TransprerException {     imagePointer[0] = image; }        };        t.setTranscodingHints(transprerHints);        t.transpre(input, null);    }    catch (TransprerException ex) {        // Requires Java 6        ex.printStackTrace();        throw new IOException("Couldn't convert " + svgFile);    }    finally {        cssFile.delete();    }    return imagePointer[0];}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5499628.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存