记录一种基于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\">\n" +
			"        <mi>f</mi>\n" +
			"            <mo>(</mo>\n" +
			"            <mi>x</mi>\n" +
			"            <mo>)</mo>\n" +
			"            <mo>&gt;</mo>\n" +
			"            <mfrac>\n" +
			"                <msqrt>\n" +
			"                    <mn>2</mn>\n" +
			"                </msqrt>\n" +
			"                <mn>8</mn>\n" +
			"            </mfrac>\n" +
			"            <mo>+</mo>\n" +
			"            <mn>1</mn>\n" +
			"        </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
posted @ 2021-06-23 09:54  布禾  阅读(637)  评论(0编辑  收藏  举报