Java生成二维码

时间:2019-11-28
本文章向大家介绍Java生成二维码,主要包括Java生成二维码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

转载: https://www.cnblogs.com/codingcc1/p/11099788.html

https://blog.csdn.net/wjs040/article/details/91452293

<dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.1</version>
        </dependency>
package com.jsy.demo.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
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.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class ZXingUtil {
    
    private static final int BLACK = 0xFF000000;//颜色
    private static final int WHITE = 0xFFFFFFFF; //背景色
    
    /**
     * 
     * @param imgPath: 本地图片路径
     * @param format: 图片类型
     * @param content: 二维码内容
     * @param width: 宽度
     * @param height: 高度
     * @param logo: logo路径
     * @throws Exception
     */
    public static void encodeImg(String imgPath,String format,String content,int width,int height,String logo) throws Exception {
        Hashtable<EncodeHintType,Object > hints = new Hashtable<EncodeHintType,Object>() ;
        //排错率  L<M<Q<H
        hints.put( EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H) ;
        //编码
        hints.put( EncodeHintType.CHARACTER_SET, "utf-8") ;
        //外边距:margin
        hints.put( EncodeHintType.MARGIN, 1) ;
        /*
         * content : 需要加密的 文字
         * BarcodeFormat.QR_CODE:要解析的类型(二维码)
         * hints:加密涉及的一些参数:编码、排错率
         */
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height, hints);
        //内存中的一张图片:此时需要的图片 是二维码-> 需要一个boolean[][] ->BitMatrix
        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)? BLACK:WHITE)  );
            }
        }
        //画logo
        image = LogoUtil.logoMatrix(image, logo) ;
        //string->file
        File file = new File(imgPath);
        //生成图片
        ImageIO.write(image, format, file);
    }

    //解密:二维码->文字
    public static void decodeImg(File file) throws Exception {
        if(!file.exists()) return ;
        //file->内存中的一张图片
        BufferedImage imge = ImageIO.read(file)  ;

        MultiFormatReader formatReader = new MultiFormatReader() ;
        LuminanceSource source = new BufferedImageLuminanceSource(imge);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        //图片 ->result
        Map map = new HashMap();
        map.put(EncodeHintType.CHARACTER_SET, "utf-8") ;
        Result result = formatReader.decode(binaryBitmap  ,map ) ;
        System.out.println("解析结果:"+ result.toString());
    }

}
ZXingUtil.Java
package com.jsy.demo.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class LogoUtil {
    //传入logo、二维码 ->带logo的二维码
    public  static BufferedImage  logoMatrix( BufferedImage matrixImage,String logo ) throws IOException {
        //在二维码上画logo:产生一个  二维码画板
        Graphics2D g2 = matrixImage.createGraphics();

        //画logo: String->BufferedImage(内存)
        BufferedImage logoImg = ImageIO.read(new File(logo));
        int height = matrixImage.getHeight();
        int width = matrixImage.getWidth();
        //纯logo图片
        g2.drawImage(convertCircular(logoImg), width * 2 / 5, height * 2 / 5, width * 1 / 5, height * 1 / 5, null);

        //产生一个 画 白色圆角正方形的 画笔
        BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        //将画板-画笔 关联
        g2.setStroke(stroke);
        //创建一个正方形
        //RoundRectangle2D.Float round = new RoundRectangle2D.Float(width * 2 / 5, height * 2 / 5, width * 1 / 5, height * 1 / 5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        
        //RoundRectangle2D.Float round = new RoundRectangle2D.Float(width * 2 / 5, height * 2 / 5, width * 1 / 5, height * 1 / 5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        
        //g2.setColor(Color.WHITE);
        //g2.draw(round);

        //灰色边框
        BasicStroke stroke2 = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        g2.setStroke(stroke2);
        //创建一个正方形
        /*RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(width * 2 / 5 + 2, height * 2 / 5 + 2, width * 1 / 5 - 4, height * 1 / 5 - 4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
        Color color = new Color(128,128,128) ;
        g2.setColor(Color.GRAY);
        g2.draw(round2);*/

        g2.dispose();
        matrixImage.flush();

        return matrixImage;
    }
    
    /**
     * 传入的图像必须是正方形的 才会 圆形  如果是长方形的比例则会变成椭圆的
     * @param bi1 用户头像地址
     * @return
     * @throws IOException
     */
    public static BufferedImage convertCircular(BufferedImage bi1) throws IOException{
        //这种是黑色底的
        //BufferedImage bi2 = new BufferedImage(bi1.getWidth(),bi1.getHeight(),BufferedImage.TYPE_INT_RGB);

        //透明底的图片
        BufferedImage bi2 = new BufferedImage(bi1.getWidth(),bi1.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
        Ellipse2D.Double shape = new Ellipse2D.Double(0,0,bi1.getWidth(),bi1.getHeight());
        Graphics2D g2 = bi2.createGraphics();
        g2.setClip(shape);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 使用 setRenderingHint 设置抗锯齿
        g2.drawImage(bi1,0,0,null);
        //设置颜色
        g2.setBackground(Color.green);
        g2.dispose();
        return bi2;
    }
}
LogoUtil.java
package com.jsy.demo;
import java.io.File;

import com.jsy.demo.utils.ZXingUtil;

public class test {
    public static void main(String[] args) throws Exception {
        String imgPath = "src/二维码test6.png";
        String content = "http://my9wby.natappfree.cc/index.html";
        String logo = "src/logo.png";
        //加密:文字信息->二维码
        ZXingUtil.encodeImg(imgPath, "png",content, 300, 300,logo);
        //解密:二维码  ->文字信息
        ZXingUtil.decodeImg(new File(imgPath));
    }
}
test.java

注意: 如果要内嵌图片的话,尽量选取高清图片,不然很模糊!

原文地址:https://www.cnblogs.com/yxgmagic/p/11950336.html