
Java二维码带文字
原先工具类只能生成一个普通的二维码
这一期说是要二维码下面要加一个文字
晚上找了一下都比较乱
还是自己稍微改了一下好一点。。
public static MultipartFile createQrCode(String content) {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
// 生成矩阵
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, IMG_WIDTH, IMG_HEIGHT, hints);
BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
//创建一个ByteArrayOutputStream
ByteArrayOutputStream os = new ByteArrayOutputStream();
//把BufferedImage写入ByteArrayOutputStream
ImageIO.write(bufferedImage, "jpg", os);
//ByteArrayOutputStream转成InputStream
InputStream input = new ByteArrayInputStream(os.toByteArray());
//InputStream转成MultipartFile
return new MockMultipartFile("file", "qrcode.jpg", "text/plain", input);
} catch (IOException | WriterException exception) {
throw new ApplicationException(exception.getMessage());
}
}
public static MultipartFile createQrCodeWithText(String content, String text) {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
// 生成矩阵
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, IMG_WIDTH, IMG_HEIGHT, hints);
BufferedImage image = pressText(text, MatrixToImageWriter.toBufferedImage(bitMatrix), Color.BLACK, FONT_SIZE, IMG_WIDTH, IMG_HEIGHT);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
InputStream input = new ByteArrayInputStream(os.toByteArray());
return new MockMultipartFile("file", "qrcode.jpg", "text/plain", input);
} catch (WriterException | IOException exception) {
throw new ApplicationException(exception.getMessage());
}
}
public static BufferedImage pressText(String pressText, BufferedImage image, Color color, int fontSize, int width, int height) {
//计算文字开始的位置
//x开始的位置:(图片宽度-字体大小*字的个数)/2
int startX = (width - (fontSize * pressText.length())) / 2;
//y开始的位置:图片高度-(图片高度-图片宽度)/2
int startY = height - (height - width) / 2 - 11;
try {
Graphics g = image.createGraphics();
g.setColor(color);
g.setFont(new Font("黑体", Font.PLAIN, fontSize));
g.drawString(pressText, startX, startY);
g.dispose();
return image;
} catch (Exception e) {
System.out.println("1111" + e);
return null;
}
}
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 Henry's Lib
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果