博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 生成文字图片
阅读量:2168 次
发布时间:2019-05-01

本文共 1467 字,大约阅读时间需要 4 分钟。

Java 生成文字图片

使用java生成指定字体的图片。具体的代码如下所示,代码中部分参数是针对英文字母设定的,如果是使用中文或者其他语言,请自行调整。

// 64 size 的值 大写宽度为40.5 我们取值稍大一点        int width = (keyword.length() + 1) * 45;        if (width < ImageAttachmentServiceImpl.IMG_HEIGHT.intValue()) {
width = ImageAttachmentServiceImpl.IMG_WIDTH; } //设置字体大小 Font font = new Font("Times New Roman", Font.PLAIN, ImageAttachmentServiceImpl.FONT_SIZE); BufferedImage image = new BufferedImage(width, ImageAttachmentServiceImpl.IMG_HEIGHT, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); g.setClip(0, 0, width, ImageAttachmentServiceImpl.IMG_HEIGHT); g.setColor(Color.white); // 先用黑色填充整张图片,也就是背景 g.fillRect(0, 0, width, ImageAttachmentServiceImpl.IMG_HEIGHT); // 在换成黑色 g.setColor(Color.black); // 设置画笔字体 g.setFont(font); /** 用于获得垂直居中y */ Rectangle clip = g.getClipBounds(); FontMetrics fm = g.getFontMetrics(font); int textWidth = fm.stringWidth(keyword); int x = (width - textWidth) / 2; int ascent = fm.getAscent(); int descent = fm.getDescent(); int y = (clip.height - (ascent + descent)) / 2 + ascent; g.drawString(keyword, x, y); g.dispose(); File file = new File(imageRootPath + keyword + ".jpg"); if (!file.exists()) {
file.mkdirs(); } // 输出png图片 ImageIO.write(image, "jpg", file);

转载地址:http://tjvzb.baihongyu.com/

你可能感兴趣的文章
win10安装软件 打开时报错 找不到 msvcp120.dll
查看>>
PHPunit+Xdebug代码覆盖率以及遇到的问题汇总
查看>>
PHPUnit安装及使用
查看>>
PHP项目用xhprof性能分析(安装及应用实例)
查看>>
composer安装YII
查看>>
Sublime text3快捷键演示
查看>>
sublime text3 快捷键修改
查看>>
关于PHP几点建议
查看>>
硬盘的接口、协议
查看>>
VLAN与子网划分区别
查看>>
Cisco Packet Tracer教程
查看>>
02. 交换机的基本配置和管理
查看>>
03. 交换机的Telnet远程登陆配置
查看>>
微信小程序-调用-腾讯视频-解决方案
查看>>
phpStudy安装yaf扩展
查看>>
密码 加密 加盐 常用操作记录
查看>>
TP 分页后,调用指定页。
查看>>
Oracle数据库中的(+)连接
查看>>
java-oracle中几十个实用的PL/SQL
查看>>
PLSQL常用方法汇总
查看>>