Skip to content

Instantly share code, notes, and snippets.

@akbertram
Created September 29, 2019 18:31
Show Gist options
  • Save akbertram/bb44ff049f9173a4d11e12ec536f079c to your computer and use it in GitHub Desktop.
Save akbertram/bb44ff049f9173a4d11e12ec536f079c to your computer and use it in GitHub Desktop.
package org.renjin;
import org.renjin.script.RenjinScriptEngine;
import javax.script.ScriptException;
public class GraphicsDeviceTest {
public static void main(String[] args) throws ScriptException {
// Initialize the engine
RenjinScriptEngine engine = new RenjinScriptEngine();
engine.eval(".mydevice <- function() grDevices:::JavaGD(deviceClass = 'org.renjin.MyDevice')");
engine.eval("options(device=.mydevice)");
// Run R code that generates the plots
engine.eval("plot(1:12)");
engine.eval("plot(1:24)");
// Shutdown the Graphics device. this will flush the last active plot
engine.eval("graphics.off()");
}
}
package org.renjin;
import org.renjin.eval.Session;
import org.renjin.grDevices.GDContainer;
import org.renjin.grDevices.GDObject;
import org.renjin.grDevices.GDState;
import org.renjin.grDevices.GraphicsDevice;
import org.renjin.sexp.ListVector;
import java.awt.*;
import java.awt.image.BufferedImage;
public class MyDevice extends GraphicsDevice {
private final Session session;
private final ListVector deviceOptions;
public MyDevice(Session session, ListVector deviceOptions) {
this.session = session;
this.deviceOptions = deviceOptions;
}
@Override
public void open(double width, double height) {
BufferedImage bufferedImage = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_ARGB);
Dimension size = new Dimension((int)width, (int)height);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setBackground(Color.WHITE);
graphics.clearRect(0, 0, (int)size.getWidth(), (int)size.getHeight());
GDState state = new GDState();
container = new GDContainer() {
private int deviceNumber;
private boolean empty = true;
@Override
public void add(GDObject o) {
empty = false;
o.paint(null, state, graphics);
}
@Override
public void reset() {
if(!empty) {
flush();
}
graphics.setClip(null);
graphics.clearRect(0, 0, (int) size.getWidth(), (int) size.getHeight());
}
@Override
public GDState getGState() {
return state;
}
@Override
public Graphics getGraphics() {
return graphics;
}
@Override
public void syncDisplay(boolean finish) {
// No action: we do not have a display
}
@Override
public void setDeviceNumber(int dn) {
this.deviceNumber = dn;
}
@Override
public void closeDisplay() {
flush();
}
@Override
public int getDeviceNumber() {
return deviceNumber;
}
@Override
public Dimension getSize() {
return size;
}
private void flush() {
System.out.println("New plot!");
// At this point you can do something with BufferedImage.
// For example, write it to a byte[] array that can be sent to the client
// when the request is complete.
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment