Java生成二维码

这篇博客介绍了如何使用Java来生成二维码,首先需要下载QRCode的jar包,然后通过代码实现生成二维码的功能,文中提供了已验证的代码示例。

一、准备工作

下载jar包:http://www.swetake.com/qrcode/

二、代码呈现

package com.test.demo1;

import com.swetake.util.*;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 使用QR Code,二维码的产生于解析
 */
public class Qecode {
    public static void main(String[] args)throws Exception{

        Qrcode x=new Qrcode();
        x.setQrcodeErrorCorrect('M');   //纠错等级:M、L、H、Q
        x.setQrcodeEncodeMode('B');     //代表数字,A代表a-Z字符,B代表其他字符
        x.setQrcodeVersion(7);      //版本号
        int width = 67 + 12 *(7-1); //固定公式,使内容与外框保持同步
        int height = 67 + 12 *(7-1);

        String qrData="http://www.baidu.com";  //定义内容

        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //画图边框
        //画图工具
        Graphics2D gs = bufferedImage.createGraphics();
        //定义画图工具属性
        gs.setBackground(Color.WHITE);  //背景颜色
        gs.setColor(Color.BLACK);       //字体颜色
        gs.clearRect(0,0,width,height);     //清除原来的内容

        int pixoff = 2; //增加偏移量
        //往面板中填充内容
        byte[] d =qrData.getBytes("gb2312");
        if (d.length>0 && d.length <120){
            boolean[][] s = x.calQrcode(d);

            for (int i=0;i<s.length;i++){
                for (int j=0;j<s.length;j++){
                    if (s[j][i]) {
                        gs.fillRect(j*3+pixoff,i*3+pixoff,3,3);
                    }
                }
            }
        }
        gs.dispose();   //结束流操作
        bufferedImage.flush();

        //打印图像
        ImageIO.write(bufferedImage,"png",new File("I:/SummerTest/test.png"));

    }
}

以上程序已验证!

### 使用 Java 生成二维码 (QR Code) 在 Java生成二维码,最常用的方法是使用 **ZXing**(Zebra Crossing)库。ZXing 是一个开源的、跨平台的条形码和二维码生成与解析库,支持多种编码格式和纠错机制。 #### 1. Maven 依赖配置 首先,在 `pom.xml` 文件中添加 ZXing 的依赖: ```xml <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.5.2</version> </dependency> ``` #### 2. 生成二维码的核心代码 以下是一个简单的 Java 示例,展示如何使用 ZXing 生成二维码并将其保存为图像文件: ```java import com.google.zxing.*; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; public class QRCodeGenerator { public static void generateQRCode(String data, String filePath, int width, int height) throws WriterException, IOException { // 设置二维码的纠错级别 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height, com.google.zxing.EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 写入文件 Path path = FileSystems.getDefault().getPath(filePath); MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); } public static void main(String[] args) { String data = "https://www.example.com"; String filePath = "qrcode.png"; int width = 300; int height = 300; try { generateQRCode(data, filePath, width, height); System.out.println("二维码生成成功!"); } catch (Exception e) { System.err.println("生成二维码失败:" + e.getMessage()); } } } ``` #### 3. 自定义二维码(添加 Logo) 如果希望在二维码中心添加 Logo,可以在生成二维码图像后,使用 `BufferedImage` 和 `Graphics2D` 将 Logo 叠加到二维码图像上: ```java import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; public class QRCodeWithLogo { public static void addLogoToQRCode(String qrCodePath, String logoPath, String outputFilePath, int logoSize) throws Exception { BufferedImage qrImage = ImageIO.read(new File(qrCodePath)); BufferedImage logo = ImageIO.read(new File(logoPath)); // 调整 Logo 大小 Image scaledLogo = logo.getScaledInstance(logoSize, logoSize, Image.SCALE_SMOOTH); BufferedImage resizedLogo = new BufferedImage(logoSize, logoSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g = resizedLogo.createGraphics(); g.drawImage(scaledLogo, 0, 0, null); g.dispose(); // 在二维码中心绘制 Logo Graphics2D graphics = qrImage.createGraphics(); int x = (qrImage.getWidth() - logoSize) / 2; int y = (qrImage.getHeight() - logoSize) / 2; graphics.drawImage(resizedLogo, x, y, null); graphics.dispose(); // 保存结果 ImageIO.write(qrImage, "PNG", new File(outputFilePath)); } public static void main(String[] args) throws Exception { String qrCodePath = "qrcode.png"; String logoPath = "logo.png"; String outputFilePath = "qrcode_with_logo.png"; int logoSize = 50; addLogoToQRCode(qrCodePath, logoPath, outputFilePath, logoSize); System.out.println("二维码添加 Logo 成功!"); } } ``` #### 4. 常见问题处理 在使用 ZXing 生成二维码时,可能会遇到如下异常: - **`data bits cannot fit in the QR Code`**:表示数据量超出了当前版本二维码的容量限制。可以通过提高二维码的版本(`Version`)或降低数据量来解决。例如,使用 `EncodeHintType.QR_VERSION` 设置更高的版本[^4]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值