FileToPngUtil.java
package simple.callback.filetopng;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class FileToPngUtil {
public static void createImageFromFile(String filePath, String outPath, Font font, int lineHeightPx, int width) throws Exception {
List list = new ArrayList<>();
try (BufferedReader br = Files.newBufferedReader(Paths.get(filePath))) {
//br returns as stream and convert it into a List
list = br.lines().collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
int height = lineHeightPx * list.size();
// 创建图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文对象
Graphics graphics = image.getGraphics();
//背景色
graphics.setColor(Color.BLACK);
// 填充
graphics.fillRect(0, 0, width, height);
// 设定字体大小及样式
graphics.setFont(font);
// 字体颜色
graphics.setColor(Color.WHITE);
for (int i = 0; i < list.size(); i++) {
// 描绘字符串
graphics.drawString(list.get(i), 0, 0 + (i + 1) * lineHeightPx);
}
graphics.dispose();
graphics.dispose();
ImageIO.write(image, "png", new File(outPath));// 输出png图片
}
//测试用例
public static void main(String[] args) throws Exception {
String prefixPath = "/home/wangyetao/IdeaProjects/psimple/src/simple/callback/filetopng/";
String fileName = "FileToPngUtil.java";
String pngName = "FileToPngUtil.png";
String inPath = prefixPath + fileName;
String outPath = prefixPath + pngName;
int lineHeightPx = 20;
int width = 1150;
createImageFromFile(inPath, outPath, new Font("微软", Font.PLAIN, 15), lineHeightPx, width);
}
}
2.输出为图片
记录与总结,2021年 10月 30日 星期六 16:40:56 CST。



