文章目录
- 【Java】Java 使用 Graphics2D 在图片上添加文字,并解决图片变红问题
- 完整案例
【Java】Java 使用 Graphics2D 在图片上添加文字,并解决图片变红问题
完整案例
public static void main(String[] args) {
try {
String filePath = "D:\\Workspace\\XunshuWorkspace\\engage\\engage-service\\uploadPath\\upload\\template\\register-certificate.jpg";
Image src = Toolkit.getDefaultToolkit().getImage(filePath);
BufferedImage image = BufferedImageBuilder.toBufferedImage(src);
Graphics2D g = image.createGraphics();
Font font = new Font("宋体", Font.BOLD, 80);
g.setFont(font);
g.setColor(Color.black);
g.drawString("张三", 500, 950);
g.drawString("522323199812345678", 1750, 950);
String date = "2024-03-01";
String end = "2024-03-11";
g.drawString(date.substring(0, 4), 550, 1150);
g.drawString(date.substring(5, 7), 950, 1150);
g.drawString(date.substring(8, 10), 1250, 1150);
g.drawString(end.substring(0, 4), 1650, 1150);
g.drawString(end.substring(5, 7), 2000, 1150);
g.drawString(end.substring(8, 10), 2350, 1150);
g.drawString("耳鼻咽喉头颈外科", 1000, 1350);
long day = DateUtil.betweenDay(DateUtil.parse(date), DateUtil.parse(end), true);
g.drawString(String.valueOf(day), 2800, 1350);
String currentDate = DateUtil.today();
g.drawString(currentDate.substring(0, 4), 2320, 2100);
g.drawString(currentDate.substring(5, 7), 2660, 2100);
g.drawString(currentDate.substring(8, 10), 2900, 2100);
g.dispose();
// ServletOutputStream outputStream = ServletUtils.getResponse().getOutputStream();
File output = new File(filePath.replace(".jpg", "-" + UUID.randomUUID() + ".jpg"));
ImageIO.write(image, "jpg", output);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 使用 ImageIO.read(file); 压缩后的图片会变红改为使用
* Toolkit.getDefaultToolkit().getImage
*/
public static class BufferedImageBuilder {
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
try {
int transparency = Transparency.OPAQUE;
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(image.getWidth(null),
image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null),
image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
}