公式转透明图片以及base64
写了个小Demo,将公式字符串例如“$$R_x=N_xP_xL_x$$”转为公式,公式见图“公式样式”。用到的jar包jlatexmath主要用来将字符串转为公式,Graphics2D主要就是用来绘制图形。
直接上代码。
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
import sun.misc.BASE64Encoder;
public class Latex2Png {
// latex 转 imgbase64
public static boolean latex2Png(String latex, String filePath) {
String suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
BufferedImage bufferedImage = latex2BuImage(latex);
if (null == bufferedImage) {
return false;
}
try {
File file = new File(filePath);
File pFile = file.getParentFile();
if (!pFile.exists()) {
pFile.mkdirs();
}
ImageIO.write(bufferedImage, suffix, file);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
// latex 转 imgbase64
public static String latex2Png(String latex) {
BufferedImage bufferedImage = latex2BuImage(latex);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "png", outputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
byte[] buffer = outputStream.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
return ("data:image/png;base64," + encoder.encode(buffer));
}
private static BufferedImage latex2BuImage(String drawStr) {
try {
TeXFormula formula = new TeXFormula(drawStr);
TeXIcon icon = formula
.createTeXIcon(TeXConstants.STYLE_DISPLAY, 40);
icon.setInsets(new Insets(5, 5, 5, 5));
int width = icon.getIconWidth();
int height = icon.getIconHeight();
JLabel jl = new JLabel();
jl.setForeground(new Color(0, 0, 0));
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D gd = buffImg.createGraphics();
buffImg = gd.getDeviceConfiguration().createCompatibleImage(width,
height, Transparency.TRANSLUCENT);
gd = buffImg.createGraphics();
gd.setColor(Color.white);
icon.paintIcon(jl, gd, 0, 0);
return buffImg;
} catch (Exception e) {
System.err.println("公式解析有误:\n" + drawStr);
e.printStackTrace();
return null;
}
}
}
代码全在这里了,也不用附件了
页:
[1]