核心工具类****
public class IOUtil {
/**
* 图片宽度
*/
private static int width =196;
/**
* 每一行的高度
*/
private static int line_height =24;
/**
* 字体
*/
private static Fontfont =new Font("宋体", Font.PLAIN, 14);
/**
* 转数组为 jpg/png
*
* @param strArr 数组
* @return void
* @date 2022/7/29 14:29
*/
public static void createImage(String[] strArr, File filepath)throws Exception {
FontMetrics fm = FontDesignMetrics.getMetrics(font);
int stringWidth = fm.charWidth('字');// 标点符号也算一个字
//计算每行多少字 = 宽/每个字占用的宽度
int line_string_num =width % stringWidth ==0 ? (width / stringWidth) : (width / stringWidth) +1;
//将数组转为list
List strList =new ArrayList<>(Arrays.asList(strArr));
//按照每行多少个字进行分割
for (int j =0; j < strList.size(); j++) {
//当字数超过限制,就进行分割
if (strList.get(j).length() > line_string_num) {
//将多的那一端放入本行下一行,等待下一个循环处理
strList.add(j +1, strList.get(j).substring(line_string_num));
//更新本行的内容
strList.set(j, strList.get(j).substring(0, line_string_num));
}
}
//计算图片的高度,多预留一行
int image_height = strList.size() *line_height +line_height;
//每张图片有多少行文字
int every_line = image_height /line_height;
// 创建图片 宽度多预留一点
BufferedImage image =new BufferedImage(width +20, image_height,
BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();
g.setClip(0, 0, width +20, image_height);
g.setColor(Color.white); // 背景色白色
g.fillRect(0, 0, width +20, image_height);
g.setColor(Color.black);// 字体颜色黑色
g.setFont(font);// 设置画笔字体
// 每张多少行,当到最后一张时判断是否填充满
for (int i =0; i < every_line; i++) {
int index = i;
if (strList.size() -1 >= index) {
// System.out.println("每行实际=" + newList.get(index).length());
g.drawString(strList.get(index), 0, line_height * (i +1));
}
}
g.dispose();
ImageIO.write(image, "png", filepath);// 输出png图片
}
}
使用方法
public static void main(String[] args)throws Exception {
String arr[] = {"aaaaa", "ccccc 13"};
//arr,生成图片的文字(以数组进行传递,每一个数组中的内容和下一个内容换行),
//生成本地的路径加文件名
createImage(arr, new File("D:/pic/1234.png"));
}