Java 生成帶文字、帶邊框的二維碼
- 1、Java 生成帶文字的二維碼
- 1.1、導入jar包
- 1.2、普通單一的二維碼
- 1.2.1、代碼示例
- 1.2.2、效果
- 1.3、帶文字的二維碼
- 1.3.1、代碼示例
- 1.3.2、效果
- 2、帶邊框的二維碼
- 2.1、代碼示例
- 2.2、帶邊框的二維碼效果
1、Java 生成帶文字的二維碼
在做一些標簽時,我們時常會用到二維碼,現在我們利用Java來生成二維碼。
1.1、導入jar包
在pom.xml中,導入zxing包
<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.4.1</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.4.1</version></dependency>
1.2、普通單一的二維碼
1.2.1、代碼示例
rHeight = 100; // 二維碼核心區域高度(不含邊距)int margin = 50; // 邊距大小(像素)// 生成二維碼(無邊距)BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrWidth, qrHeight);BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);// 創建帶邊距的畫布int totalWidth = qrWidth ;int totalHeight = qrHeight ;BufferedImage finalImage = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);Graphics2D graphics = finalImage.createGraphics();graphics.setColor(Color.WHITE);graphics.fillRect(0, 0, totalWidth, totalHeight); // 填充背景// 將二維碼繪制到畫布中央(可調整位置)graphics.drawImage(qrImage, 0, 0, null);graphics.dispose();// 保存圖像ImageIO.write(finalImage, "PNG", new File("測試.png"));}
1.2.2、效果
1.3、帶文字的二維碼
1.3.1、代碼示例
/*** 二維碼屬性設置 * @param text 內容* @param width 寬度* @param height 高度* @return* @throws WriterException*/private static BitMatrix generateQRCode(String text, int width, int height) throws WriterException {Map<EncodeHintType, Object> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //字符集
// hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容錯率hints.put(EncodeHintType.MARGIN, 0);// 禁用ZXing默認邊距return new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);}
//二維碼圖上帶字public static void contextLoads(String name,String path) {String textToEncode = name;int qrCodeWidth = 100;int qrCodeHeight = 100;int textPadding = 10; // 文本與二維碼之間的間距int textSize = 10; // 文本字體大小int totalHeight = qrCodeHeight + textPadding;try {// 生成二維碼的BitMatrixBitMatrix bitMatrix = generateQRCode(textToEncode, qrCodeWidth, qrCodeHeight);// 將BitMatrix轉換為BufferedImageBufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);// 創建一個新的BufferedImage來容納二維碼和文本BufferedImage combinedImage = new BufferedImage(qrCodeWidth, totalHeight, BufferedImage.TYPE_INT_RGB);// 繪制二維碼到新的BufferedImage上Graphics2D g2d = combinedImage.createGraphics();g2d.setColor(Color.WHITE);g2d.fillRect(0, 0, qrCodeWidth, totalHeight);g2d.drawImage(qrCodeImage, 0, 0, null);// 設置文本樣式Font font = new Font("Arial", Font.PLAIN, textSize);g2d.setFont(font);g2d.setColor(Color.BLACK); // 文本顏色// 繪制文本到圖片下方FontMetrics metrics = g2d.getFontMetrics();int textX = (qrCodeWidth - metrics.stringWidth(textToEncode)) / 2;int textY = qrCodeHeight + textPadding;g2d.drawString(textToEncode, textX, textY);g2d.dispose();// 指定存儲圖片的路徑Path filePath = Paths.get(path+name+".png");// 確保文件路徑的父目錄存在filePath.getParent().toFile().mkdirs();// 保存圖片到文件ImageIO.write(combinedImage, "PNG", filePath.toFile());System.out.println("QR Code with text has been generated: " + filePath.toAbsolutePath());} catch (WriterException | IOException e) {e.printStackTrace();}}
public static void main(String[] args) {// 指定存儲二維碼圖片的路徑String filePath = "D:/data/";contextLoads("C40851-WZ-A01",filePath);}
1.3.2、效果
2、帶邊框的二維碼
因為我將生成的二維碼圖片導出到excel表格的時候,二維碼圖片覆蓋了excel表格的邊框,顯得很突兀,所以我考慮將二維碼圖片加個邊框,在導出的時候,二維碼邊框可以替代excel邊框。
2.1、代碼示例
我們在帶文字的二維碼生成類里面新增一些內容,并更詳細的增加了一些注釋。
/*** 二維碼屬性設置 * @param text 內容* @param width 寬度* @param height 高度* @return* @throws WriterException*/private static BitMatrix generateQRCode(String text, int width, int height) throws WriterException {Map<EncodeHintType, Object> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //字符集//默認邊距是為了二維碼能更好的識別,如果禁用默認邊距,為了能更好識別,最好要設置高容錯率
// hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容錯率hints.put(EncodeHintType.MARGIN, 0);// 禁用ZXing默認邊距 不禁用會有較多空白區域return new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);}
/*** 二維碼圖上帶字* @param name 二維碼 生成的內容 和 二維碼上的文字 及 二維碼的名稱* @param path 二維碼保存的路徑*/public static void contextLoads2(String name,String path) {int qrCodeWidth = 100; //二維碼寬度int qrCodeHeight = 100;//二維碼高度int textPadding = 10; // 文本與二維碼之間的間距int textSize = 10; // 文本字體大小int borderWidth=1;//邊框大小int totalHeight = qrCodeHeight + textPadding;//總高度 加上文本二維碼之間的間距try {// 生成二維碼的BitMatrixBitMatrix bitMatrix = generateQRCode(name, qrCodeWidth, qrCodeHeight);// 將BitMatrix轉換為BufferedImageBufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);// 3. 創建帶邊框的圖像int borderedSize = totalHeight + 2 * borderWidth;//因為borderedSize 包含了textPadding// 所以把寬度設置為borderedSize時,兩邊空白太多了,所以減掉了BufferedImage image = new BufferedImage(borderedSize-textPadding,borderedSize,BufferedImage.TYPE_INT_RGB);Graphics2D graphics = image.createGraphics();// 4. 繪制黑色邊框graphics.setColor(Color.BLACK);// 起始 x y 寬度 高度graphics.fillRect(0, 0, borderedSize, borderedSize);// 繪制二維碼到新的BufferedImage上Graphics2D g2d = image.createGraphics();g2d.setColor(Color.WHITE);// 起始 x y 寬度 高度g2d.fillRect(borderWidth, borderWidth, qrCodeWidth, totalHeight);g2d.drawImage(qrCodeImage, borderWidth, borderWidth, null);// 設置文本樣式Font font = new Font("Arial", Font.PLAIN, textSize);g2d.setFont(font);g2d.setColor(Color.BLACK); // 文本顏色// 繪制文本到圖片下方FontMetrics metrics = g2d.getFontMetrics();// x 居中位置int textX = (qrCodeWidth - metrics.stringWidth(name)) / 2 +borderWidth;int textY = qrCodeHeight + textPadding;g2d.drawString(name, textX, textY);g2d.dispose();// 指定存儲圖片的路徑Path filePath = Paths.get(path+name+".png");// 確保文件路徑的父目錄存在filePath.getParent().toFile().mkdirs();// 保存圖片到文件ImageIO.write(image, "PNG", filePath.toFile());System.out.println("QR Code with text has been generated: " + filePath.toAbsolutePath());} catch (WriterException | IOException e) {e.printStackTrace();}}
2.2、帶邊框的二維碼效果
以上就是本文的全部內容,部分代碼是利用AI生成,然后再去修改成我想要的效果,如果有侵權的地方,還請聯系本人。
如果代碼有異常,或者有其他疑惑、或有新思路的同學,可以評論區留言。