Here you can find the source of getStringImage(Font font, String... strs)
public static BufferedImage getStringImage(Font font, String... strs)
//package com.java2s; //License from project: Open Source License import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.*; public class Main { public static BufferedImage getStringImage(Font font, String... strs) { BufferedImage image = new BufferedImage(1, 1, 6); Graphics graphics = image.getGraphics(); graphics.setFont(font);/*from w w w. j ava2s. c o m*/ FontRenderContext fontRenderContext = graphics.getFontMetrics().getFontRenderContext(); Rectangle2D rectangle2D = font.getStringBounds(getStringArrayMaxLengthString(strs), fontRenderContext); graphics.dispose(); int width = (int) Math.ceil(rectangle2D.getWidth()); int height = 0; for (int i = 0; i < strs.length; i++) { height += (int) Math.ceil(rectangle2D.getHeight()); } return new BufferedImage(width, height, 6); } public static String getStringArrayMaxLengthString(String[] strs) { java.util.List<Integer> list = new ArrayList<>(); Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < strs.length; i++) { list.add(strs[i].length()); map.put(strs[i].length(), strs[i]); } Collections.sort(list); return map.get(list.get(list.size() - 1)); } }