Java采用自定义字体与二维码画图并输出为base64字符串
好久没更新~
话不多说,直接上代码:
// 画图
// 1.基本参数
int width = 1240; // 图像宽
int height = 1754; // 图像高
int keyX = 150; // key的x位置
int valueX = 430; // value的x位置
int lineY = 400; // 行的y位置
int lineHeight = 70; // 行高
// 2.创建图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE); // 背景色
graphics.fillRect(0, 0, width, height); // 填充背景色
graphics.setColor(Color.BLACK); // 设置文字颜色
// 3.设置字体(这里采用的是加载resources文件夹下的字体文件)
InputStream is = getClass().getClassLoader().getResourceAsStream("font/msyhbd.ttf");
Font fieldFont = Font.createFont(Font.TRUETYPE_FONT, is);
is = getClass().getClassLoader().getResourceAsStream("font/msyhbd.ttf");
Font titleFont = Font.createFont(Font.TRUETYPE_FONT, is);
graphics.setFont(fieldFont.deriveFont(33f));
// 4.填充文字
graphics.drawString("属性1", keyX, lineY);
graphics.drawString("值1", valueX, lineY);
lineY += lineHeight;
graphics.drawString("属性2", keyX, lineY);
graphics.drawString("值2", valueX, lineY);
lineY += lineHeight;
graphics.drawString("属性3", keyX, lineY);
graphics.drawString("值3", valueX, lineY);
lineY += lineHeight;
graphics.drawString("属性4", keyX, lineY);
graphics.drawString("值4", valueX, lineY);
// 5.写入条形码
Code128Writer writer = new Code128Writer();
BitMatrix bitMatrix = writer.encode("1234567890", BarcodeFormat.CODE_128, 100, 50);
MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig();
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix, matrixToImageConfig);
graphics.drawImage(bufferedImage, 660, 220, 480, 80, null);
graphics.setFont(titleFont.deriveFont(28f));
graphics.drawString("1234567890", 790, 340);
// 6.返回base64
String base64Image = "";
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(image, "png", outputStream);
byte[] imageBytes = outputStream.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageBytes);
} catch (IOException e) {
e.printStackTrace();
}
return base64Image;
** Then I looked up at the sky and saw the sun **
posted on 2023-07-25 16:39 chenyangsocool 阅读(151) 评论(0) 编辑 收藏 举报