Java提供了将图形转储为jpg格式的功能, 但这种格式不是矢量格式,没办法在word等软件中修改,编辑。
word中的矢量图形格式是wmf(Windows Meta File)。这种格式主要由一个或两个information headers组成,结构如下: typedef struct _WindowsMetaHeader
{
WORD FileType; /* Type of metafile (0=memory, 1=disk) */
WORD HeaderSize; /* Size of header in WORDS (always 9) */
WORD Version; /* Version of Microsoft Windows used */
DWORD FileSize; /* Total size of the metafile in WORDs */
WORD NumOfObjects; /* Number of objects in the file */
DWORD MaxRecordSize; /* The size of largest record in WORDs */
WORD NumOfParams; /* Not Used (always 0) */
} WMFHEAD;
除了headers之外下面就是文件记录(Standard Metafile Records)。结构如下: typedef struct _StandardMetaRecord
{
DWORD Size; /* Total size of the record in WORDs */
WORD Function; /* Function number (defined in WINDOWS.H) */
WORD Parameters[]; /* Parameter values passed to function */
} WMFRECORD;
也就是说每一个record中储存的是Windows GDI绘图函数的代码及每个函数对应的参数.这样的 话整个wmf文件就由这样的函数编码与参数组成。就像下面这样: Record Name | Function Number |
---|
AbortDoc | 0x0052 | Arc | 0x0817 | Chord | 0x0830 | DeleteObject | 0x01f0 | Ellipse | 0x0418 |
... 了解了wmf文件的格式,我们就清楚我们如何将我们的图形储存为wmf格式了。我们知道在 JAVA中所有的绘图操作都是通过Graphics来完成的。基本上Graphics中的每一个绘图函数 在Windows GDI中都有对应,我们只需继承一个Graphics类,重载它的每一个方法,转成 对应的Windwos GDI函数,就可以达到我们的目的了。 Graphics中的函数很多,工作量巨大,不用怕,网上已有人写好了,大家请到: http://piet.jonas.com去下载一个WMFWriter吧。 下载后,将它加到classpath,再请使用我写的这个类,轻松的将你的图形存为wmf格式: /** * Copyright: Copyright (c) 2002 * Company: * @author Turbo Chen
* @version 1.0
*/
public class WMFWriter { /** comp是你的图形所在的JComponent,out是你指定的输出流
public void write(JComponent comp, OutputStream out) throws Exception { try { int w = comp.getSize().width; int h = comp.getSize().height; WMF wmf = new WMF(); WMFGraphics wmfgraphics = new WMFGraphics(wmf, w, h); comp.paint(wmfgraphics); wmf.writePlaceableWMF(out, 0, 0, w, h, Toolkit.getDefaultToolkit().getScreenResolution()); wmfgraphics.dispose(); out.close(); } catch(Exception exception) { throw new Exception("GRAPHICS ERROR,CAN NOT CREATE WMF FORMAT"); } } }

|