Use Org. eclipse. draw2d. swtgraphics class and org. eclipse. SWT. graphics. the imageloader class can be used to export a canvas to an image file. The principle is to create a blank image in the memory, draw the divisor, and save it to the specified file and format.
We can divide the export work into two parts. The first part is responsible for providing the ifigure instance to be exported (to export the entire canvas, obtain printable_layers from graphicalviewer; otherwise, the line on the canvas will be lost ), write the obtained image data to a file. The second part is responsible for converting the ifigure instance to the image data. Example of the formerCode:
String filename =...; Practiceeditor Editor=...; Scalablefreeformrooteditpart rootpart=...; Ifigure figure= Rootpart. getlayer (scalablefreeformrooteditpart. printable_layers );//To ensure every graphical element is wrongly DEDByte[] DATA =Createimage (figure, SWT. image_png );Try{Fileoutputstream fos=NewFileoutputstream (filename); FOS. Write (data); FOS. Close ();}Catch(Ioexception e) {e. printstacktrace ();}
The createimage () method called in the code above is the place where the image is actually painted in the memory and converted to a binary stream that can be written as a file. The Code is as follows:
Private Byte [] Createimage (ifigure figure, Int Format) {rectangle R = Figure. getbounds (); bytearrayoutputstream result = New Bytearrayoutputstream (); image = Null ; GC = Null ; Graphics g = Null ; Try {Image = New Image ( Null , R. Width, R. Height); GC = New GC (image); G = New Swtgraphics (GC); G. Translate (R. x *-1, R. y *-1 ); Figure. Paint (g); imageloader = New Imageloader (); imageloader. Data =New Imagedata [] {image. getimagedata ()}; imageloader. Save (result, format );} Finally { If (G! = Null ) {G. Dispose ();} If (GC! = Null ) {GC. Dispose ();} If (Image! = Null ) {Image. Dispose ();}} Return Result. tobytearray ();}
Click here to download the project. This project is modified from gefpractice in the GEF application instance, and the extension of the target file is. gefpractice.
Figure 1 Export button added after running
Related links in the GEF news group:
Http://dev.eclipse.org/newslists/news.eclipse.tools.gef/msg05012.html
Http://dev.eclipse.org/newslists/news.eclipse.tools.gef/msg06329.html