9.30

今天学习java生成二维码

import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class QRCodeGenerator { public static void main(String[] args) { // 创建 QRCodeWriter 对象 QRCodeWriter qrCodeWriter = new QRCodeWriter(); // 设置要编码的数据和编码类型 String data = "https://example.com"; String format = "PNG"; try { // 生成 BitMatrix 对象 BitMatrix bitMatrix = qrCodeWriter.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, 200, 200); // 设置保存图片的路径 Path path = Paths.get("qrcode.png"); // 生成二维码图像并保存 MatrixToImageWriter.writeToPath(bitMatrix, format, path); System.out.println("QR code generated successfully at " + path.toFile().getAbsolutePath()); // 如果需要显示图像,可以将其转换为 BufferedImage 并使用 GUI 组件显示 BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix); // 例如使用 Swing 的 JLabel 组件显示 // new ImageIcon(image).getImage(); } catch (WriterException | IOException e) { e.printStackTrace(); } } }

 

这个例子会生成一个 QR 码,并将其保存到当前目录下的 qrcode.png 文件中。如果希望直接在应用中显示这个图像而不是保存到文件,可以将生成的 BufferedImage 对象传递给相应的图形界面组件进行显示。

请注意,这段代码需要 ZXing 的 jar 包才能运行。如果你使用 Maven 或者 Gradle 管理依赖,可以像之前那样添加相应的依赖项。

如果你在运行过程中遇到任何问题,比如找不到类或者运行时异常,请确保你已经正确安装了所需的库,并且库的版本与你的 Java 环境兼容。

posted @ 2024-09-30 20:19  混沌武士丞  阅读(1)  评论(0编辑  收藏  举报