声明:此文章参考自八进制在博客园发表的"GEF常见问题8:导出到图片 "一文,原文地址为:http://bjzhanghao.cnblogs.com/category/36197.html。
本人较懒,且相关知识八进制前辈的文中已有说明,不再累赘,直接贴代码:
public void run() {
FileDialog dialog = new FileDialog(Display.getDefault().getActiveShell(), SWT.SAVE);
dialog.setFilterNames(new String[] { "PNG(*.png)" });
dialog.setFilterExtensions(new String[] { "*.png", "*.*" });
String fileName = dialog.open();
// 根据指定文件和图片类型输出图片
exportDiagramAsImage(fileName, SWT.IMAGE_PNG);
}
/**
* 根据指定文件和图片类型输出图片
* @param fileName
* @param type
*/
private void exportDiagramAsImage(String fileName, int type) {
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if(editor instanceof GraphicalEditPart){
GraphicalViewer graphicalViewer =(GraphicalViewer)editor.getAdapter(GraphicalViewer.class);;
if(graphicalViewer.getRootEditPart() instanceof ScalableFreeformRootEditPart){
ScalableFreeformRootEditPart rootEditPart = (ScalableFreeformRootEditPart)graphicalViewer.getRootEditPart();
IFigure figure = rootEditPart.getLayer(ScalableFreeformRootEditPart.PRINTABLE_LAYERS);
byte[] data = createImage(figure, type);
try {
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(data);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private byte[] createImage(IFigure figure, int format) {
Rectangle rectangle = figure.getBounds();
ByteArrayOutputStream result = new ByteArrayOutputStream();
Image image = null;
GC gc = null;
Graphics graphics = null;
try {
image = new Image(null, rectangle.width, rectangle.height);
gc = new GC(image);
graphics = new SWTGraphics(gc);
graphics.translate(rectangle.x * -1, rectangle.y * -1);
figure.paint(graphics);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] { image.getImageData() };
imageLoader.save(result, format);
} finally {
if (graphics != null) {
graphics.dispose();
}
if (gc != null) {
gc.dispose();
}
if (image != null) {
image.dispose();
}
}
return result.toByteArray();
}