生成二维码需要两个jar包
Download core JAR 3.5.1 ➔ With all dependencies!
Download javase JAR 3.5.1 ➔ With all dependencies!
将下载后的jar包添加项目依赖
import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class QrCodeDemo1 {
public static void main(String[] args) {
//支持中文
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, "1");
//生成二维码
int w = 220;
int h = 220;
//text可以直接写文字,二维码扫出即为文字,或者放视频或图片地址,则二维码扫出为图片或视频
String text =
"http://img1.baidu.com/it/u=1828664006,303765003&fm=253&fmt=auto&app=138&f=JPEG? w=800&h=500";
try {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix encode = writer.encode(text, BarcodeFormat.QR_CODE, w, h, hints);
BufferedImage img = MatrixToImageWriter.toBufferedImage(encode);
//二维化格式new File("qr1.jpg")可选择图片地址,不写默认当前目录下
ImageIO.write(img, "jpg", new File("qr1.jpg"));
} catch (Exception e) {
}
}
}
解析二维码
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class QrCodeDemo2 {
public static void main(String[] args) {
try {
//qr1.jpg刚生成的二维码图片
BufferedImage i = ImageIO.read(new File("qr1.jpg"));
LuminanceSource source = new BufferedImageLuminanceSource(i);
BinaryBitmap image = new BinaryBitmap(new HybridBinarizer(source));
Result result = new MultiFormatReader().decode(image);
String info = result.getText();
System.out.println(info);
if (info == null || "".equals(info)) {
System.out.println("没有二维码信息");
} else if (info.contains("weixin")) { //qq mp
System.out.println("有微信二维码,不允许");
} else {
System.out.println("有二维,可以使用");
}
} catch (Exception e) {
System.out.println("图像中没有二维码");
}
}
}
可以判断图片中是否有二维码信息