java生成二维码

使用Google开源库zxing生成二维码

  1. pom.xml文件中添加以下依赖:

    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>core</artifactId>
        <version>2.1</version>
    </dependency>
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>javase</artifactId>
        <version>2.1</version>
    </dependency>
    
  2. 生成二维码,并将logo嵌入

    private static byte[] createQRCode(String url) throws Exception {

    QRCodeWriter writer = new QRCodeWriter();
    HashMap<EncodeHintType, Object> m = new HashMap<EncodeHintType, Object>();
    m.put(EncodeHintType.CHARACTER_SET, com.tencent.jungle.quntribe.helper.CommonUtil.UTF8);
    
    // 按最大尺寸生成
    BitMatrix bm = writer.encode(url, BarcodeFormat.QR_CODE, 600, 600, m);
    MatrixToImageConfig config = new MatrixToImageConfig(BufferedImage.TYPE_INT_RGB, MatrixToImageConfig.WHITE);
    BufferedImage image = MatrixToImageWriter.toBufferedImage(bm, config);
    Graphics2D m2 = image.createGraphics();
    BufferedImage overlay = ImageIO.read(new URL(BULUO_LOGO_IMAGE)/*new File("D://Penguins.jpg")*/);
    int deltaHeight = image.getHeight() - overlay.getHeight();
    int deltaWidth = image.getWidth()  - overlay.getWidth();
    
    m2.drawImage(image, 0, 0, null);
    m2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
    m2.setColor(Color.WHITE);
    m2.drawImage(overlay, (int) Math.round(deltaWidth / 2),
            (int) Math.round(deltaHeight / 2), null);
    
    m2.dispose();
    
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
    ImageIO.write(image, "png", buffer);
    return buffer.toByteArray();
    

    }

    这里有几个点需要注意:

  • 构造函数要使用可以指定颜色区间的:(否则会导致产生黑白的图片)
    MatrixToImageConfig config = new MatrixToImageConfig(BufferedImage.TYPE_INT_RGB, MatrixToImageConfig.WHITE);
  • setComposite设置对应位置关系,要使用AlphaComposite.SRC_OVER,这样,logo才不会被后面的二维码所覆盖
    参见:Compositing Graphics