java使用zxing生成二维码,可带logo和底部文字
生活随笔
收集整理的這篇文章主要介紹了
java使用zxing生成二维码,可带logo和底部文字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java使用zxing生成二維碼,可帶logo和底部文字
springboot中整合zxing生成二維碼
一、導入依賴
<properties><zxing.version>3.4.0</zxing.version> </properties><!--二維碼依賴--><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>${zxing.version}</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>${zxing.version}</version></dependency>二、二維碼工具類封裝QRCodeUtil.java,支持生成BufferedImage 和byte[]
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import lombok.SneakyThrows; import org.springframework.core.io.ClassPathResource; import org.springframework.util.StringUtils; import sun.font.FontDesignMetrics;import javax.imageio.ImageIO; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.HashMap;/*** 二維碼生成工具類* Created by chenzan on 2022/09/19*/ public class QRCodeUtil {private static final int QRCODE_SIZE = 320; // 二維碼尺寸,寬度和高度均是320private static final String FORMAT_TYPE = "PNG"; // 二維碼圖片類型/*** 默認需要logo,無底部文字* 返回 BufferedImage 可以使用ImageIO.write(BufferedImage, "png", outputStream);輸出** @param dataStr* @return 返回 BufferedImage 可以使用ImageIO.write(BufferedImage, "png", outputStream);輸出*/@SneakyThrowspublic static BufferedImage getQRCodeImage(String dataStr) {BufferedImage bufferedImage = getQRCodeImage(dataStr, true, null);return bufferedImage;}/*** 默認需要logo,無底部文字** @param dataStr* @return 返回字節數組*/@SneakyThrowspublic static byte[] getQRCodeByte(String dataStr) {BufferedImage bufferedImage = getQRCodeImage(dataStr, true, null);ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ImageIO.write(bufferedImage, FORMAT_TYPE, outputStream);byte[] byteData = outputStream.toByteArray();return byteData;}/*** 默認需要logo,包含底部文字 文字為空則不顯示文字* 返回 BufferedImage 可以使用ImageIO.write(BufferedImage, "png", outputStream);輸出** @param dataStr* @return*/@SneakyThrowspublic static BufferedImage getQRCodeImage(String dataStr, String bottomText) {BufferedImage bufferedImage = getQRCodeImage(dataStr, true, bottomText);return bufferedImage;}/*** 默認需要logo,包含底部文字 文字為空則不顯示文字** @param dataStr* @return 返回字節數組*/@SneakyThrowspublic static byte[] getQRCodeByte(String dataStr, String bottomText) {BufferedImage bufferedImage = getQRCodeImage(dataStr, true, bottomText);ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ImageIO.write(bufferedImage, FORMAT_TYPE, outputStream);byte[] byteData = outputStream.toByteArray();return byteData;}/*** 獲取二維碼圖片** @param dataStr 二維碼內容* @param needLogo 是否需要添加logo* @param bottomText 底部文字 為空則不顯示* @return*/@SneakyThrowspublic static BufferedImage getQRCodeImage(String dataStr, boolean needLogo, String bottomText) {if (dataStr == null) {throw new RuntimeException("未包含任何信息");}HashMap<EncodeHintType, Object> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //定義內容字符集的編碼hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); //定義糾錯等級hints.put(EncodeHintType.MARGIN, 1);QRCodeWriter qrCodeWriter = new QRCodeWriter();BitMatrix bitMatrix = qrCodeWriter.encode(dataStr, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();int tempHeight = height;if (StringUtils.hasText(bottomText)) {tempHeight = tempHeight + 12;}BufferedImage image = new BufferedImage(width, tempHeight, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);}}// 判斷是否添加logoif (needLogo) {insertLogoImage(image);}// 判斷是否添加底部文字if (StringUtils.hasText(bottomText)) {addFontImage(image, bottomText);}return image;}/*** 插入logo圖片** @param source 二維碼圖片* @throws Exception*/private static void insertLogoImage(BufferedImage source) throws Exception {// 默認logo放于resource/static/image目錄下ClassPathResource classPathResource = new ClassPathResource("static/image/logo.png");InputStream inputStream = classPathResource.getInputStream();if (inputStream == null || inputStream.available() == 0) {return;}Image src = ImageIO.read(inputStream);int width = 30;int height = 30;Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(image, 0, 0, null); // 繪制縮小后的圖g.dispose();src = image;// 插入LOGOGraphics2D graph = source.createGraphics();int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(src, x, y, width, height, null);Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}private static void addFontImage(BufferedImage source, String declareText) {//生成imageint defineWidth = QRCODE_SIZE;int defineHeight = 20;BufferedImage textImage = new BufferedImage(defineWidth, defineHeight, BufferedImage.TYPE_INT_RGB);Graphics2D g2 = (Graphics2D) textImage.getGraphics();//開啟文字抗鋸齒g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);g2.setBackground(Color.WHITE);g2.clearRect(0, 0, defineWidth, defineHeight);g2.setPaint(Color.BLACK);FontRenderContext context = g2.getFontRenderContext();//部署linux需要注意 linux無此字體會顯示方塊Font font = new Font("宋體", Font.BOLD, 15);g2.setFont(font);LineMetrics lineMetrics = font.getLineMetrics(declareText, context);FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);float offset = (defineWidth - fontMetrics.stringWidth(declareText)) / 2;float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;g2.drawString(declareText, (int) offset, (int) y);Graphics2D graph = source.createGraphics();//開啟文字抗鋸齒graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//添加imageint width = textImage.getWidth(null);int height = textImage.getHeight(null);Image src = textImage;graph.drawImage(src, 0, QRCODE_SIZE - 8, width, height, Color.WHITE, null);graph.dispose();}}三、使用
//1、生成帶logo和底部文字得二維碼@SneakyThrows@GetMapping("/getQrCode1")public void getQrCode1(HttpServletResponse response) {ServletOutputStream os = response.getOutputStream();BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage("test", "底部文字");response.setContentType("image/png");ImageIO.write(bufferedImage,"png",os);}//2、生成不帶logo和底部文字得二維碼@SneakyThrows@GetMapping("/getQrCode2")public void getQrCode2(HttpServletResponse response) {ServletOutputStream os = response.getOutputStream();BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage("test", false);response.setContentType("image/png");ImageIO.write(bufferedImage,"png",os);} //3、生成默認帶logo不帶底部文字得二維碼@SneakyThrows@GetMapping("/getQrCode3")public void getQrCode3(HttpServletResponse response) {ServletOutputStream os = response.getOutputStream();BufferedImage bufferedImage = QRCodeUtil.generateQRCodeImage("test");response.setContentType("image/png");ImageIO.write(bufferedImage,"png",os);} //3、生成不帶logo帶底部文字得二維碼@SneakyThrows@GetMapping("/getQrCode3")public void getQrCode3(HttpServletResponse response) {ServletOutputStream os = response.getOutputStream();BufferedImage bufferedImage = QRCodeUtil.getQRCodeImage("test",false, "底部文字");response.setContentType("image/png");ImageIO.write(bufferedImage,"png",os);}直接請求即可得到二維碼圖片
四、文字在linux下得展示問題
在jdk中加入指定的字體(宋體)
在jdk目錄(/usr/local/jdk1.8.0_331/jre/lib/fonts)下創建目錄fallback
將window下的宋體字體放到此目錄下
字體文件位于:C:\Windows\Fonts
總結
以上是生活随笔為你收集整理的java使用zxing生成二维码,可带logo和底部文字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android 手机查看sql数据库 以
- 下一篇: 奈雪的茶上市了,资本愿意砸钱,营销策略做