本文共 1467 字,大约阅读时间需要 4 分钟。
// 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/