Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java 生成二维码图片

作者:浪推晚风   发布日期:2025-02-06   浏览:120

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

public class QRCodeGenerator {

    public static void main(String[] args) {
        String data = "https://www.example.com"; // 二维码要包含的数据
        int width = 300; // 图片宽度
        int height = 300; // 图片高度
        String filePath = "qrcode.png"; // 输出文件路径

        try {
            createQRCode(data, width, height, filePath);
            System.out.println("二维码图片已生成!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createQRCode(String data, int width, int height, String filePath) throws Exception {
        // 设置二维码的参数
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        // 创建BitMatrix对象
        BitMatrix matrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height, hints);

        // 创建BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = image.createGraphics();

        // 设置背景色为白色
        graphics.setColor(java.awt.Color.WHITE);
        graphics.fillRect(0, 0, width, height);

        // 设置前景色为黑色,并绘制二维码
        graphics.setColor(java.awt.Color.BLACK);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                if (matrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }

        // 将BufferedImage保存为PNG格式的文件
        File file = new File(filePath);
        ImageIO.write(image, "png", file);
    }
}

代码解释:

  1. 导入必要的库:使用了 com.google.zxing 包来生成二维码,javax.imageio.ImageIO 用于图像处理。
  2. 设置二维码内容和图片尺寸:定义了二维码中包含的数据、图片的宽度和高度以及输出文件路径。
  3. 创建二维码:通过 MultiFormatWriter 类生成二维码的 BitMatrix 对象,并设置了字符集为 UTF-8。
  4. 绘制二维码:创建一个 BufferedImage 对象并使用 Graphics2D 绘制二维码。背景色设为白色,前景色设为黑色。
  5. 保存二维码图片:将生成的二维码图片保存为 PNG 文件。

注意事项:

  • 需要引入 zxing 库,可以通过 Maven 或直接下载 jar 包引入。
  • 二维码内容可以根据需要进行修改。

上一篇:java 拆分字符串

下一篇:java mqtt协议

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站