核心工具類****
public class IOUtil {
/**
? ? * 圖片寬度
? ? */
? ? private static int width =196;
? ? /**
? ? * 每一行的高度
? ? */
? ? private static int line_height =24;
? ? /**
? ? * 字體
? ? */
? ? private static Fontfont =new Font("宋體", Font.PLAIN, 14);
? ? /**
? ? * 轉(zhuǎn)數(shù)組為 jpg/png
*
? ? * @param strArr 數(shù)組
? ? * @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('字');// 標(biāo)點(diǎn)符號(hào)也算一個(gè)字
? ? ? ? //計(jì)算每行多少字 = 寬/每個(gè)字占用的寬度
? ? ? ? int line_string_num =width % stringWidth ==0 ? (width / stringWidth) : (width / stringWidth) +1;
? ? ? ? //將數(shù)組轉(zhuǎn)為list
? ? ? ? List strList =new ArrayList<>(Arrays.asList(strArr));
? ? ? ? //按照每行多少個(gè)字進(jìn)行分割
? ? ? ? for (int j =0; j < strList.size(); j++) {
//當(dāng)字?jǐn)?shù)超過限制送膳,就進(jìn)行分割
? ? ? ? ? ? if (strList.get(j).length() > line_string_num) {
//將多的那一端放入本行下一行丑蛤,等待下一個(gè)循環(huán)處理
? ? ? ? ? ? ? ? strList.add(j +1, strList.get(j).substring(line_string_num));
? ? ? ? ? ? ? ? //更新本行的內(nèi)容
? ? ? ? ? ? ? ? strList.set(j, strList.get(j).substring(0, line_string_num));
? ? ? ? ? ? }
}
//計(jì)算圖片的高度,多預(yù)留一行
? ? ? ? int image_height = strList.size() *line_height +line_height;
? ? ? ? //每張圖片有多少行文字
? ? ? ? int every_line = image_height /line_height;
? ? ? ? // 創(chuàng)建圖片? 寬度多預(yù)留一點(diǎn)
? ? ? ? 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);// 設(shè)置畫筆字體
? ? ? ? // 每張多少行,當(dāng)?shù)阶詈笠粡垥r(shí)判斷是否填充滿
? ? ? ? for (int i =0; i < every_line; i++) {
int index = i;
? ? ? ? ? ? if (strList.size() -1 >= index) {
//? ? ? ? ? ? ? ? ? ? System.out.println("每行實(shí)際=" + 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名斟,生成圖片的文字(以數(shù)組進(jìn)行傳遞砰盐,每一個(gè)數(shù)組中的內(nèi)容和下一個(gè)內(nèi)容換行)坑律,
? ? ? ? //生成本地的路徑加文件名
? ? ? ? createImage(arr, new File("D:/pic/1234.png"));
? ? }