java - 我如何优化 batik svg 以便它可以生成小文件
问题描述
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGeneratorContext;
import org.apache.batik.svggen.SVGGraphics2D;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXFormula.TeXIconBuilder;
import org.scilab.forge.jlatexmath.TeXIcon;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
public class jlatexmath {
private final static String SVG_NS = "http://www.w3.org/2000/svg";
private final static String SVG_ROOT = "svg";
private final static float FONT_SIZE = 20;
private String renderLatex(String source) {
DOMImplementation DOMImpl = GenericDOMImplementation.getDOMImplementation();
Document document = DOMImpl.createDocument(SVG_NS, SVG_ROOT, null);
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
SVGGraphics2D g = new SVGGraphics2D(ctx, true);
TeXFormula formula = new TeXFormula(source);
TeXFormula.TeXIconBuilder builder = formula.new TeXIconBuilder();
builder.setStyle(TeXConstants.STYLE_DISPLAY);
builder.setSize(FONT_SIZE);
TeXIcon icon = builder.build();
icon.setInsets(new Insets(0, 0, 0, 0));
g.setSVGCanvasSize(new Dimension(icon.getIconWidth(), icon.getIconHeight()));
g.setColor(new Color(0, 0, 0, 0));
g.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
icon.paintIcon(null, g, 0, 0);
StringWriter out = new StringWriter();
try {
g.stream(out, true);
out.flush();
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return out.toString();
}
public static void main(String[] args) throws IOException {
String latex = "(a+b)^{2}=a^{2}+2ab+b^{2}";
jlatexmath j = new jlatexmath();
String svgString = j.renderLatex(latex);
Files.write(Paths.get("D:/latex.svg"), svgString.getBytes());
System.out.println(svgString);
}
}
我正在使用 jlatexmath-1.0.7 来生成可以正常工作的乳胶图像。但我需要 svg 输出,所以我使用 apache batik 相同,上面的代码正在生成 ~17KB 文件。一些在线工具,如 codecogs.com,为相同的乳胶输入生成约 7KB 的 svg。如何从 java 中的 svg 中删除不必要的信息,以便生成更小的图像。
解决方案
您是否尝试过传入false
构造函数SVGGraphics2D(ctx, true)?它使用文本而不是图形,因此生成的文件大小也更小。
推荐阅读
- macos - 在 MAC 电脑上使用终端复制/粘贴
- php - ## 之后使用 php 删除部分字符串?
- javascript - 仅将一个数组中的某些元素复制到javascript中的另一个数组
- javascript - TypeError:传播不可迭代实例和合成事件的无效尝试
- javascript - 无法将节点 fs 模块与 k6 一起使用
- c - 控制可能到达非空函数的结尾。C
- python-3.x - 为什么它不能正确读取 xml 数据?
- node.js - 只允许有效的 firebase 用户访问我的 Nodejs API
- flutter - Flutter RangeSlider - 标签始终显示在轨迹栏上方
- python - How can i search tensorflow's corresponding api message as a string about layer in my program?