记录一种基于Java的MathML转图片的方法
Maven依赖:
<dependency>
<groupId>de.rototor.jeuclid</groupId>
<artifactId>jeuclid-core</artifactId>
<version>3.1.14</version>
</dependency>
示例:
@Test
public void testMathMlToImg() throws IOException {
//MathML字符串
String mathStr = "<math xmlns="http://www.w3.org/1998/Math/MathML">
" +
" <mi>f</mi>
" +
" <mo>(</mo>
" +
" <mi>x</mi>
" +
" <mo>)</mo>
" +
" <mo>></mo>
" +
" <mfrac>
" +
" <msqrt>
" +
" <mn>2</mn>
" +
" </msqrt>
" +
" <mn>8</mn>
" +
" </mfrac>
" +
" <mo>+</mo>
" +
" <mn>1</mn>
" +
" </math>";
//创建转换器
Converter converter = Converter.getInstance();
//创建layoutContext并设置相关参数
//参数设置可以参考net.sourceforge.jeuclid.context.Parameter类
//参数默认值可以参考LayoutContextImpl类构造方法
LayoutContextImpl layoutContext = (LayoutContextImpl) LayoutContextImpl.getDefaultLayoutContext();
//设置公式字体大小,默认12.0pt
layoutContext.setParameter(Parameter.MATHSIZE, 30);
//设置公式颜色,默认黑色
layoutContext.setParameter(Parameter.MATHCOLOR, Color.RED);
//转换
Dimension dimension = converter.convert(mathStr, new FileOutputStream("f:/1.png"), "image/png", layoutContext);
if(dimension != null){
System.out.println("图片转换成功!高:" + dimension.getHeight() + " 宽:" + dimension.getWidth());
}
}
输出结果:
图片转换成功!高:70.0 宽:149.0
转换结果如下:
关于outFileType参数的取值,支持以下几种:
image/png
image/vnd.wap.wbmp
image/x-png
image/jpeg
image/tiff
image/bmp
image/gif