当然,首先要导入zxing的jar包。
生成二维码代码:
package com.imooc.zxing; import java.io.File; import java.nio.file.Path; import java.util.HashMap; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * java代码生成二维码<br> * * @author Administrator * */ public class CreateQRCode { public static void main(String[] args) { int width = 300; int height = 300; String format = "png"; String content = "http://www.hupu.com"; // 定义二维码参数 HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 字符集 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 纠错级别 hints.put(EncodeHintType.MARGIN, 2);// 空白 try { BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); Path file = new File("E:/code/img.png").toPath(); MatrixToImageWriter.writeToPath(bitMatrix, format, file); } catch (Exception e) { e.printStackTrace(); } } }
生成二维码如下:
读取二维码:
package com.imooc.zxing; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import javax.imageio.ImageIO; import com.google.zxing.BinaryBitmap; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.HybridBinarizer; public class ReadQRCode { public static void main(String[] args) { try { MultiFormatReader formatReader = new MultiFormatReader(); File file = new File("E:/code/img.png"); BufferedImage image = ImageIO.read(file); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer( new BufferedImageLuminanceSource(image))); HashMap hints = new HashMap(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 字符集 Result result = formatReader.decode(binaryBitmap, hints); System.out.println("解析之后的结果:" + result.toString()); System.out.println("二维码格式类型:" + result.getBarcodeFormat()); System.out.println("二维码文本内容:" + result.getText()); } catch (Exception e) { e.printStackTrace(); } } }
代码运行结果: