美文网首页
java 使用zxing 生成二维码

java 使用zxing 生成二维码

作者: 郝小永 | 来源:发表于2019-01-10 17:03 被阅读0次

源码地址 https://github.com/zxing/zxing

项目的文档中也说明了,java主要模块是在 core和 javase中,
我们打开 QRCodeWriterTestCase
可以看到生成二维码的方法.

public final class QRCodeWriterTestCase extends Assert {

  private static final Path BASE_IMAGE_PATH = Paths.get("src/test/resources/golden/qrcode/");

  private static BufferedImage loadImage(String fileName) throws IOException {
    Path file = BASE_IMAGE_PATH.resolve(fileName);
    if (!Files.exists(file)) {
      // try starting with 'core' since the test base is often given as the project root
      file = Paths.get("core/").resolve(BASE_IMAGE_PATH).resolve(fileName);
    }
    assertTrue("Please download and install test images, and run from the 'core' directory", Files.exists(file));
    return ImageIO.read(file.toFile());
  }

  // In case the golden images are not monochromatic, convert the RGB values to greyscale.
  private static BitMatrix createMatrixFromImage(BufferedImage image) {
    int width = image.getWidth();
    int height = image.getHeight();
    int[] pixels = new int[width * height];
    image.getRGB(0, 0, width, height, pixels, 0, width);

    BitMatrix matrix = new BitMatrix(width, height);
    for (int y = 0; y < height; y++) {
      for (int x = 0; x < width; x++) {
        int pixel = pixels[y * width + x];
        int luminance = (306 * ((pixel >> 16) & 0xFF) +
            601 * ((pixel >> 8) & 0xFF) +
            117 * (pixel & 0xFF)) >> 10;
        if (luminance <= 0x7F) {
          matrix.set(x, y);
        }
      }
    }
    return matrix;
  }

  @Test
  public void testQRCodeWriter() throws WriterException {
    // The QR should be multiplied up to fit, with extra padding if necessary
    int bigEnough = 256;
    Writer writer = new QRCodeWriter();
    BitMatrix matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, bigEnough,
        bigEnough, null);
    assertNotNull(matrix);
    assertEquals(bigEnough, matrix.getWidth());
    assertEquals(bigEnough, matrix.getHeight());

    // The QR will not fit in this size, so the matrix should come back bigger
    int tooSmall = 20;
    matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, tooSmall,
        tooSmall, null);
    assertNotNull(matrix);
    assertTrue(tooSmall < matrix.getWidth());
    assertTrue(tooSmall < matrix.getHeight());

    // We should also be able to handle non-square requests by padding them
    int strangeWidth = 500;
    int strangeHeight = 100;
    matrix = writer.encode("http://www.google.com/", BarcodeFormat.QR_CODE, strangeWidth,
        strangeHeight, null);
    assertNotNull(matrix);
    assertEquals(strangeWidth, matrix.getWidth());
    assertEquals(strangeHeight, matrix.getHeight());
  }

  private static void compareToGoldenFile(String contents,
                                          ErrorCorrectionLevel ecLevel,
                                          int resolution,
                                          String fileName) throws WriterException, IOException {

    BufferedImage image = loadImage(fileName);
    assertNotNull(image);
    BitMatrix goldenResult = createMatrixFromImage(image);
    assertNotNull(goldenResult);

    Map<EncodeHintType,Object> hints = new EnumMap<>(EncodeHintType.class);
    hints.put(EncodeHintType.ERROR_CORRECTION, ecLevel);
    Writer writer = new QRCodeWriter();
    BitMatrix generatedResult = writer.encode(contents, BarcodeFormat.QR_CODE, resolution,
        resolution, hints);

    assertEquals(resolution, generatedResult.getWidth());
    assertEquals(resolution, generatedResult.getHeight());
    assertEquals(goldenResult, generatedResult);
  }

  // Golden images are generated with "qrcode_sample.cc". The images are checked with both eye balls
  // and cell phones. We expect pixel-perfect results, because the error correction level is known,
  // and the pixel dimensions matches exactly. 
  @Test
  public void testRegressionTest() throws Exception {
    compareToGoldenFile("http://www.google.com/", ErrorCorrectionLevel.M, 99,
        "renderer-test-01.png");
  }

}

我这里在进行封装一下,我们使用zxing时要引入

<dependency>
  <groupId>com.google.zxing</groupId>
 <artifactId>javase</artifactId>
 <version>3.3.3</version>
</dependency>

下面是我再次进行封装的工具类:

public class QRCodeUtils {

    /**
     * 保存二维码图片到指定的路径
     * @param filePath 指定的路径
     * @param content 二维码的内存(字符串)
     */
    public void createQRCode(String filePath, String content) {
        int width=300;              //图片的宽度
        int height=300;             //图片的高度
        String format="png";        //图片的格式\

        /**
         * 定义二维码的参数
         */
        HashMap hints=new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET,"utf-8");    //指定字符编码为“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(filePath).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public String getContentFromQRCode(String filePath) {
        MultiFormatReader formatReader=new MultiFormatReader();
        File file=new File(filePath);
        BufferedImage image;
        try {
            image = ImageIO.read(file);
            BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer
                                    (new BufferedImageLuminanceSource(image)));
            HashMap hints=new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET,"utf-8");    //指定字符编码为“utf-8”
            Result result=formatReader.decode(binaryBitmap,hints);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

使用方法:

String content="user_code:3";
String qrCodeFilePath = C:/Users/Administrator/ + 文件名 + ".png";//临时存放目录
QRCodeUtils qrCodeUtils=new QRCodeUtils();
qrCodeUtils.createQRCode(qrCodeFilePath, content);

由于二维码不能放了,所以就不放图片了。。。。。

相关文章

网友评论

      本文标题:java 使用zxing 生成二维码

      本文链接:https://www.haomeiwen.com/subject/slbarqtx.html