Java 生成文字图片

阅读: 评论:0

Java 生成文字图片

Java 生成文字图片

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 = Graphics();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 (!ists()) {file.mkdirs();}// 输出png图片ImageIO.write(image, "jpg", file);

本文发布于:2024-01-29 17:29:52,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170652059617078.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:文字   图片   Java
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23