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 环境兼容。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
2023-07-13 周四总结