hady_ 2016-07-14 01:17 采纳率: 0%
浏览 2223
已结题

Java 外部字体加载后输出图片字体无法识别到

楼主做报表,用的ireport,需要用到条形码,由于条码下方的字体用到OCR-B 10 BT这个字体,
外部写一个条码工具集成到ireport.
barcode4j/zxing 下方的条码字体需要自己画上去
但是Font加载OCR-B 10 BT.ttf字体后,测试了下输出效果,结果图片的字体无法正常显示。图片说明

public static String create(String str, String filePath, int width, int height) throws Exception{

    String fileName = System.currentTimeMillis() + ".jpg";
    String path = filePath + "/" + fileName;
    File file = new File(path);
    BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) bi.getGraphics();
    g2.setBackground(Color.WHITE);
    g2.clearRect(0, 0, width, height);
    String ttf = "C:/Users/Administrator/Desktop/OCR-B 10 BT/OCR-B 10 BT.ttf";
//        Font font = new Font("OCR-B 10 Pitch BT", Font.BOLD, 25);//OCR-B 10 Pitch BT
    Font font = Font.createFont(Font.TRUETYPE_FONT, new File(ttf));
    font = font.deriveFont(Font.BOLD, 12); // 粗体比Font.PLAIN清晰
//        FileInputStream aixing = new FileInputStream(new File("C:/Users/Administrator/Desktop/tt0646z_/tt0646z_.ttf"));
//        Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, aixing);
//        Font font = dynamicFont.deriveFont(25);
    g2.setFont(font);
    g2.setPaint(Color.RED);

    FontRenderContext context = g2.getFontRenderContext();
    Rectangle2D bounds = font.getStringBounds(str, context);
    double x = (width - bounds.getWidth()) / 2;
    double y = (height - bounds.getHeight()) / 2;
    double ascent = -bounds.getY();
    double baseY = y + ascent;

    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.drawString(str, (int) x, (int) baseY);
    try {
        ImageIO.write(bi, "png", file);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
//            fb.close();
//            fi.close();
    }
    return file.getPath();
}

  • 写回答

2条回答 默认 最新

  • _1_1_7_ 2016-07-14 01:44
    关注

    估计是字体并没有加载成功,你的代码呢?

    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型