Mar 18, 2008

Exporting GEF figure to an image

Quite often you need to export the current contents of a GEF editor to an image. Here is the simple code to do that:



GraphicalViewer graphicalViewer = ...; // get it from your editor

String saveLocation = ...; // get it thru a FileDialog


ScalableFreeformRootEditPart rootEditPart = (ScalableFreeformRootEditPart) graphicalViewer.getEditPartRegistry().get(LayerManager.ID);


IFigure rootFigure = ((LayerManager) rootEditPart).getLayer(LayerConstants.PRINTABLE_LAYERS);


Rectangle rootFigureBounds = rootFigure.getBounds();


Control figureCanvas = graphicalViewer.getControl();




Image img = new Image(Display.getDefault(), rootFigureBounds.width, rootFigureBounds.height);


GC imageGC = new GC(img);


figureCanvas.print(imageGC); // This is Eclipse 3.4 only API



ImageLoader imgLoader = new ImageLoader();

imgLoader.data = new ImageData[] { img.getImageData() };


imgLoader.save(saveLocation, SWT.IMAGE_JPEG);



imageGC.dispose();


img.dispose();






Just in case you need, here is a nice image to represent this Action :-)

3 comments:

ajay said...

How to Export GEF figure to an image in eclipse version 3.3 ?

Regards,
Ajay Kemparaj

Prakash G.R. said...

You can get it from here:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=115066

GraphicalViewer graphicalViewer = myEditor.getGraphicalViewer();

ScalableFreeformRootEditPart rootEditPart = (ScalableFreeformRootEditPart) graphicalViewer.getEditPartRegistry().get(LayerManager.ID);
IFigure rootFigure = ((LayerManager) rootEditPart).getLayer(LayerConstants.PRINTABLE_LAYERS);
Rectangle rootFigureBounds = rootFigure.getBounds();

Control figureCanvas = graphicalViewer.getControl();
GC figureCanvasGC = new GC(figureCanvas);

Image img = new Image(null, rootFigureBounds.width, rootFigureBounds.height);
GC imageGC = new GC(img);
imageGC.setBackground(figureCanvasGC.getBackground());
imageGC.setForeground(figureCanvasGC.getForeground());
imageGC.setFont(figureCanvasGC.getFont());
imageGC.setLineStyle(figureCanvasGC.getLineStyle());
imageGC.setLineWidth(figureCanvasGC.getLineWidth());
imageGC.setXORMode(figureCanvasGC.getXORMode());
Graphics imgGraphics = new SWTGraphics(imageGC);

rootFigure.paint(imgGraphics);

ImageData[] imgData = new ImageData[1];
imgData[0] = img.getImageData();

ImageLoader imgLoader = new ImageLoader();
imgLoader.data = imgData;
imgLoader.save(saveLocation, SWT.IMAGE_JPEG);

figureCanvasGC.dispose();
imageGC.dispose();
img.dispose();

ajay said...

Thanks Prakash