我试图获取所有英文字体的列表并用它们打印一些字符串。
这是我用来创建字符串图像的代码:
public static BufferedImage imageForString (String str, Font font) {
font = new Font(font.getName(), font.getStyle(), 400); //Can't trust people to size their own font -_-
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int width = fm.stringWidth(str);
int height = fm.getHeight();
g2d.dispose();
try {
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
} catch (Exception e) {
System.err.println("Problem printing: " + str + " " + "with font: " + font);
e.printStackTrace();
}
g2d = img.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, img.getWidth(), img.getHeight());
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
g2d.drawString(str, 0, fm.getAscent());
g2d.dispose();
return img;
}
我试图以系统所能提供的能够显示英文文本的每种字体分别打印字母表中的每个字母。这显然不起作用,因为我不断在我放置try / catch块的行上抛出异常。
我用它来获取系统所有字体的列表(显然它包含其他语言?):
public static final Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
这里引发了异常:
Problem printing: ' with font: java.awt.Font[family=Al Bayan,name=AlBayan,style=plain,size=400]
java.lang.IllegalArgumentException: Width (0) and height (601) cannot be <= 0
at java.awt.image.DirectColorModel.createCompatibleWritableRaster(DirectColorModel.java:999)
at java.awt.image.BufferedImage.<init>(BufferedImage.java:326)
at HashMaker.imageForString(HashMaker.java:48)
at HashMaker.getImgs(HashMaker.java:69)
at HashMaker.main(HashMaker.java:83)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.IntegerInterleavedRaster.getDataElements(IntegerInterleavedRaster.java:201)
at java.awt.image.BufferedImage.getRGB(BufferedImage.java:911)
at ImageUtils.colIsWhite(ImageUtils.java:23)
at ImageUtils.parseImage(ImageUtils.java:40)
at Letter.<init>(Letter.java:24)
at HashMaker.main(HashMaker.java:85)`
不仅仅是单引号,拉丁字符例如“J&#39;”也会引发例外情况。