try with resource是一个语法糖,可以使用该方式关闭流的前提是对象一定要实现AutoCloseable接口,其原理还是在编译的时候JDK给我们生成了finally来关闭流
源代码
public static String createImg(String message, int width, int height) {
String img = "";
ClassPathResource resource = new ClassPathResource("resources/font/SourceHanSansCN-Normal.ttf");
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
InputStream fis = resource.getInputStream()){
//创建画布
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//得到它的绘制环境(这张图片的笔)
Graphics2D g2 = (Graphics2D) bi.getGraphics();
//设置透明背景
bi = g2.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2 = bi.createGraphics();
Font font = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, fis);
font = font.deriveFont(Font.PLAIN, 90);
//设置字体:字体、字号、大小
g2.setFont(font);
//设置背景颜色
g2.setColor(Color.red);
int locY = g2.getFontMetrics().getHeight();
drawString(g2, message, 0, locY, width - g2.getFontMetrics().charWidth(' '));
// 输出png图片
ImageIO.write(bi, "png", outputStream);
img = Base64.encode(outputStream.toByteArray());
g2.dispose();
} catch (IOException | FontFormatException e) {
e.printStackTrace();
}
return img;
}
反编译class的文件
public static String createImg(String message, int width, int height) {
String img = "";
ClassPathResource resource = new ClassPathResource("resources/font/SourceHanSansCN-Normal.ttf");
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Throwable var6 = null;
try {
InputStream fis = resource.getInputStream();
Throwable var8 = null;
try {
BufferedImage bi = new BufferedImage(width, height, 1);
Graphics2D g2 = (Graphics2D)bi.getGraphics();
bi = g2.getDeviceConfiguration().createCompatibleImage(width, height, 3);
g2 = bi.createGraphics();
Font font = Font.createFont(0, fis);
font = font.deriveFont(0, 90.0F);
g2.setFont(font);
g2.setColor(Color.red);
int locY = g2.getFontMetrics().getHeight();
drawString(g2, message, 0, locY, width - g2.getFontMetrics().charWidth(' '));
ImageIO.write(bi, "png", outputStream);
img = Base64.encode(outputStream.toByteArray());
g2.dispose();
} catch (Throwable var36) {
var8 = var36;
throw var36;
} finally {
if (fis != null) {
if (var8 != null) {
try {
fis.close();
} catch (Throwable var35) {
var8.addSuppressed(var35);
}
} else {
fis.close();
}
}
}
} catch (Throwable var38) {
var6 = var38;
throw var38;
} finally {
if (outputStream != null) {
if (var6 != null) {
try {
outputStream.close();
} catch (Throwable var34) {
var6.addSuppressed(var34);
}
} else {
outputStream.close();
}
}
}
} catch (FontFormatException | IOException var40) {
var40.printStackTrace();
}
return img;
}