Java生成二维码

需要用到Qrcode这个文件jar放在web-inf下面的lib文件夹下面,同时,需要创建的是web项目


package com;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;


import javax.imageio.ImageIO;


import com.swetake.util.Qrcode;


/**
 * Java开发微信二维码扫一扫生成器
 * @version 1.0
 * @author Administrator
 *
 */
public class QrcodeTest {



/**
* 根据内容生成二维码图片
* @param contents 内容
* @param imgPath 生成图片存储的服务器地址
*/

public static void getQrcodeImgBycontents(
String contents,String imgPath){

int width=140;
int height=140;

try{
//实例化Qrcode new
Qrcode qrCode=new Qrcode();
//设置二维码的排错率 可选项L(7%),M(15%),Q(25%),H(30%)
qrCode.setQrcodeErrorCorrect('M');
qrCode.setQrcodeEncodeMode('B');

//设置二维码的尺寸 取值范围[1-40]
qrCode.setQrcodeVersion(7);
//设置图片的尺寸
BufferedImage bufImg=new BufferedImage(
width,height,BufferedImage.TYPE_INT_BGR);

//绘制二维码图片
Graphics2D gs=bufImg.createGraphics();
//设置二维码矩形区域的背景颜色,设置为白色
gs.setBackground(Color.WHITE);
//创建一个图片的矩形区域
gs.clearRect(0, 0, width, height);
//设置二维码的颜色
gs.setColor(Color.BLACK);


//获取内容,通过一个数组的形式 设置编码
byte[] contentBytes=contents.getBytes("gb2312");

//设置一个偏移量(如果不设置可能会导致解析错误)
int pixoff=2;

//输出二维码
if(contentBytes.length>0 && contentBytes.length<120){
boolean[][] codeOut=qrCode.calQrcode(contentBytes);
for(int i=0;i<codeOut.length;i++){
for(int j=0;j<codeOut.length;j++){//被中间那个j害惨了,把它写成了i
if(codeOut[j][i]==true){
gs.fillRect(j*3+pixoff, i*3+pixoff, 3, 3);
}
}
}
}else{
System.out.println("出错了,可能是您的内容长度超出了最大限制!");
}

gs.dispose();
bufImg.flush();
//生成二维码的Qrcode图片
File imgFile=new File(imgPath);
if(!imgFile.exists()) imgFile.createNewFile(); 
ImageIO.write(bufImg, "png", imgFile);
System.out.println("生成二维码成功!");

}catch(Exception e){
e.getStackTrace();
e.printStackTrace();
}

}


//Java程序的入口函数
public static void main(String[] args){

System.out.println("Hello World!");

String contents="hello,my name is Xiaowen!";
String imgPath="D:\\Java_Tanzhou\\Xiaowen_Qrcode\\images\\xiaowen04.png";

getQrcodeImgBycontents(contents,imgPath);
System.out.println("Hello World!");
}


}







































### 使用 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]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值