Tuesday, 27 April 2010

Creating PNGs from Jmol


Jmol is a fantastic open source 3D viewer for chemical structures. I've exported images from the application many times, both as PNGs and for rendering with POV-Ray, but after a bit of digging and trial & error I've figured out how to automate the process...

// Create the objects
java.awt.Canvas display = new Canvas();
org.jmol.adapter.smarter.SmarterJmolAdapter adapter = new SmarterJmolAdapter();
org.jmol.viewer.Viewer viewer = (Viewer)
Viewer.allocateViewer(display, adapter, null, null, null, null, null);
try {
viewer.setScreenDimension(new Dimension(1, 1));
viewer.scriptWait("load 'crystal.cif' {1 1 1};");
// can do more scripting here...
viewer.setScreenDimension(new Dimension(400, 400));

// anti-aliasing enabled
viewer.getGraphics3D().setWindowParameters(400, 400, true);

// Create image
viewer.getImageAs("PNG", 1, 400, 400, "image.png", null);
} finally {
// Ensure threads are stopped
viewer.setModeMouse(JmolConstants.MOUSE_NONE);
}

Using Jena3D's script for automatic orientation of structures, recently mentioned by Rolf Huehne on the Jmol-users mailing list I've been able to create some great pictures of crystal structures:

If only there was a really easy way for these to be used as place-holders for a lazy-loading Jmol applets, making websites embedding Jmol really fast... any volunteers?!