当前位置: 代码迷 >> 综合 >> goole zxing 生成二维码
  详细解决方案

goole zxing 生成二维码

热度:18   发布时间:2023-12-03 09:09:47.0

参考文章:
https://juejin.im/post/6847902218704977928
https://www.jianshu.com/p/124f93d8d5b9
https://www.codenong.com/cs106357124

简单的二维码生成和解码

package test;import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;import javax.imageio.ImageIO;import org.junit.Test;import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;public class QRCodeTest {
    @Testpublic void qrcode() {
    QRCodeWriter qrCodeWriter = new QRCodeWriter();BitMatrix bitMatrix;try {
    bitMatrix = qrCodeWriter.encode("my name", BarcodeFormat.QR_CODE, 500, 500);File path = new File("E:/qrcode/test.png");if(!path.getParentFile().exists()) {
    path.getParentFile().mkdirs();}MatrixToImageWriter.writeToFile(bitMatrix, "PNG", path);} catch (Exception e) {
    e.printStackTrace();}}@Testpublic void decodeQrcode() {
    BufferedImage image = null;     Result result = null;     try {
         image = ImageIO.read(new File("E:/qrcode/test.png"));     if (image == null) {
         System.out.println("the decode image may be not exit.");     }     LuminanceSource source = new BufferedImageLuminanceSource(image);     BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));     Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();     hints.put(DecodeHintType.CHARACTER_SET, "GBK");     result = new MultiFormatReader().decode(bitmap, hints);System.out.println(result.getText());} catch (Exception e) {
         e.printStackTrace();     }     }@Testpublic void barcode() {
    BitMatrix bitMatrix;try {
    bitMatrix = new MultiFormatWriter().encode("123456", BarcodeFormat.CODE_128,500,500);MatrixToImageWriter.writeToFile(bitMatrix, "png", new File("E:/barcode.png")); } catch (Exception e) {
    e.printStackTrace();}}@Testpublic void decodeBarcode() {
    BufferedImage image = null;     Result result = null;     try {
         image = ImageIO.read(new File("E:/barcode.png"));     if (image == null) {
         System.out.println("the decode image may be not exit.");     }     LuminanceSource source = new BufferedImageLuminanceSource(image);     BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));     result = new MultiFormatReader().decode(bitmap, null);     System.out.println(result.getText());} catch (Exception e) {
         e.printStackTrace();     }     }}

复杂二维码生成代码

package qrcode;import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;import javax.imageio.ImageIO;import org.apache.commons.lang.StringUtils;
import org.junit.Test;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;public class QRCodeUtils {
    /*** 生成二维码**/public static BufferedImage getImg(String content, int size) throws Exception {
    //其他参数,如字符集编码Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");//容错级别(H为最高级别)hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);//白边的宽度,可取0~4hints.put(EncodeHintType.MARGIN, 0);//生成矩阵BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size, hints);int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000: 0xFFFFFFFF);}}return image;}/*** 二维码byte**/public static byte[] getByte(BufferedImage img) throws Exception {
    ByteArrayOutputStream bao = new ByteArrayOutputStream();ImageIO.write(img, "png", bao);return bao.toByteArray();}/*** 二维码带logo* @param img* @param logoPath* @return* @throws IOException*/public static BufferedImage withLogo(BufferedImage img, String logoPath) throws IOException{
    int matrixWidth = img.getWidth();int matrixHeigh = img.getHeight();//读取Logo图片BufferedImage logo = ImageIO.read(new File(logoPath));//读取二维码图片,并构建绘图对象Graphics2D g2 = img.createGraphics();//开始绘制图片g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);// 设置笔画对象g2.setStroke(stroke);//指定弧度的圆角矩形RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);g2.setColor(Color.white);// 绘制圆弧矩形g2.draw(round);//设置logo 有一道灰色边框BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);// 设置笔画对象g2.setStroke(stroke2);RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);g2.setColor(new Color(128,128,128));// 绘制圆弧矩形g2.draw(round2);g2.dispose();img.flush();return img;}/*** 二维码带底部文字*/public static BufferedImage withButtomText(BufferedImage img, String text,int fontSize,int fonttype) throws IOException {
    int matrixWidth = img.getWidth();int matrixHeigh = img.getHeight();//新的图片下面加上文字BufferedImage outImage = new BufferedImage(matrixWidth, matrixHeigh+fontSize+60, BufferedImage.TYPE_4BYTE_ABGR);Graphics2D outg = outImage.createGraphics();outg.setBackground(Color.WHITE);outg.clearRect(0,0,outImage.getWidth(), outImage.getHeight());//画二维码到新的面板outg.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);outg.setColor(Color.BLACK);//字体、字型、字号outg.setFont(new Font("宋体",fonttype,fontSize));outg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿outg.setPaint(new Color(0, 0, 0, 64));//阴影颜色int strWidth = outg.getFontMetrics().stringWidth(text);//画文字到新的面板outg.drawString(text, (matrixWidth-strWidth)/2 , matrixHeigh+(outImage.getHeight()-matrixHeigh)/2+20);outg.setPaint(Color.BLACK);//正文颜色outg.drawString(text, (matrixWidth-strWidth)/2 , matrixHeigh+(outImage.getHeight()-matrixHeigh)/2+20);outg.dispose();outImage.flush();img = outImage;img.flush();return img;}@Testpublic void createQrcode() {
    try {
    OutputStream out = new FileOutputStream("E:/qr1.png");out.write(getByte(withButtomText( getImg("my name", 1000), "这是一个中文啊啊啊啊啊啊啊啊啊啊啊啊 啊啊啊",40,Font.BOLD)));out.flush();out.close();} catch (Exception e) {
    // TODO Auto-generated catch blocke.printStackTrace();}}}