Render a Node to BufferedImage in JavaFX 1.2

In the EffectsPlayground sample in javafx.com, there is a function saveImage(node:Node, file:java.io.File), but it does not work in JavaFX 1.2, because the internal implementation details was changed.

I write a new function that works in JavaFX 1.2:

import com.sun.javafx.geom.Bounds2D;
import com.sun.javafx.geom.AffineTransform;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javafx.scene.*;
import javafx.reflect.*;
import javafx.util.Math;

public function toRenderedImage(node:Node):RenderedImage {
    def context = FXLocal.getContext();
    def nodeClass = FXLocal.getContext().findClass("javafx.scene.Node");
    def getFXNode = nodeClass.getFunction("impl_getPGNode");
    def sgNode = (getFXNode.invoke(context.mirrorOf(node)) as FXLocal.ObjectValue).asObject();
    def getBounds = sgNode.getClass().getMethod("getCompleteBounds", Bounds2D.class, AffineTransform.class);
    def bounds = getBounds.invoke(sgNode, new Bounds2D(), null) as Bounds2D;
    def paintMethod = sgNode.getClass().getMethod("render", Graphics2D.class, Bounds2D.class, AffineTransform.class);
    def img = new BufferedImage(Math.ceil(bounds.getWidth()), Math.ceil(bounds.getHeight()), BufferedImage.TYPE_INT_RGB);
    def g2 = img.createGraphics();
    g2.translate(-bounds.x1, -bounds.y1);
    paintMethod.invoke(sgNode, g2, bounds, new AffineTransform());
    g2.dispose();
    img;
}

public function savePNG(node:Node, os:OutputStream) {
    ImageIO.write(toRenderedImage(node), "png", os);
}

public function savePNG(node:Node, file:File) {
    var savefile;
    if (not file.getName().toLowerCase().endsWith(".png")) {
        savefile = new File(file.getParent(), "{file.getName()}.png");
    } else {
        savefile = file;
    }
    savePNG(node, new FileOutputStream(savefile));
}

你可能感兴趣的:(java,OS,sun,JavaFX)