@maohoo LaTex转Image
程序员文章站
2022-05-28 12:58:06
...
package com.hunter.latexdemo;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
/**
* Created by MaoHoo on 2017/10/10.
* Description :
* Version: V1.0
*/
public class LatexRender {
public static void main(String[] args) {
String latex = "x=\\frac{-b \\pm \\sqrt {b^2-4ac}}{2a}";
// create a formula
TeXFormula formula = new TeXFormula(latex);
// render the formla to an icon of the same size as the formula.
TeXIcon icon = formula
.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
// insert a border
icon.setInsets(new Insets(5, 5, 5, 5));
// now create an actual image of the rendered equation
BufferedImage image = new BufferedImage(icon.getIconWidth(),
icon.getIconHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2 = image.createGraphics();
g2.setColor(Color.white);
g2.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
JLabel jl = new JLabel();
jl.setForeground(new Color(0, 0, 0));
icon.paintIcon(jl, g2, 0, 0);
// at this point the image is created, you could also save it with ImageIO
saveImage(image,"gif","D:\\temp\\1.gif");
}
public static void saveImage(BufferedImage image, String format,
String filePath) {
try {
ImageIO.write(image, format, new File(filePath));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}