Java自动生成二维码总结

推荐一篇博客:Java自动生成带log的二维码 https://mp.csdn.net/postedit/84454677

第一种简单的方法: 


import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.UUID;

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;

public class weweima2 {
	 public static void createQrCode(int width, int height, String content) {

	        // 1、设置二维码的一些参数
	        HashMap hints = new HashMap();
	        // 1.1设置字符集
	        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
	        // 1.2设置容错等级;因为有了容错,在一定范围内可以把二维码p成你喜欢的样式
	        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
	        // 1.3设置外边距;(即白色区域)
	        hints.put(EncodeHintType.MARGIN, 1);
	        // 2、生成二维码
	        try {
	            // 2.1定义BitMatrix对象
	            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
	            
	            // 2.2、设置二维码存放路径,以及二维码的名字
	            Path codePath = new File("E:/erweima/2" + UUID.randomUUID().toString().substring(0,4) + ".png").toPath();

	            // 2.3、执行生成二维码
	            MatrixToImageWriter.writeToPath(bitMatrix, "png", codePath);

	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }

	    }
	public static void main(String []args) {
		 createQrCode(200, 200, "https://www.baidu.com");
		
	}
}

第二种


import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Scanner;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

/*实现输入字符串(文本,网址)生成对应的二维码
 * 二维码实质是01代码,具有4个等级的容错能力
 * 二维码具有容错功能,当二维码图片被遮挡一部分后,仍可以扫描出来。
 *容错的原理是二维码在编码过程中进行了冗余,就像是123被编码成123123,这样只要扫描到一部分二维码图片,
 *二维码内容还是可以被全部读到。
 *二维码容错率即是指二维码图标被遮挡多少后,仍可以被扫描出来的能力。容错率越高,则二维码图片能被遮挡的部分越多。
 *二维码容错率用字母表示,容错能力等级分为:L、M、Q、H四级
 * */
public class CreateQrcode {
    public static void main(String[] args) throws Exception {
        // 创建生成二维码的对象
        Qrcode x = new Qrcode();
        // 设置二维码的容错能力等级
        x.setQrcodeErrorCorrect('M');
        // N代表的是数字,A代表的是a-z,B代表的是其他字符
        x.setQrcodeEncodeMode('B');
        // 版本
        x.setQrcodeVersion(7);
        // 设置验证码内容 可以输入多次
        Scanner scanner = new Scanner(System.in);
        // String str = scanner.nextLine(); //只能输入一次
        while (scanner.hasNext()) {
            String str = scanner.nextLine();
            // 设置验证码的大小
            int width = 67 + 12 * (7 - 1);
            int height = 67 + 12 * (7 - 1);
            // 定义缓冲区图片
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            // 设置画图工具
            Graphics2D gs = bufferedImage.createGraphics();
            // 设置二维码背景颜色
            gs.setBackground(Color.white);//lightGray
            // 设置颜色
            gs.setColor(Color.black);//cyan,green,red,black,pink
            // 清除画板内容
            gs.clearRect(0, 0, width, height);
            // 定义偏移量
            int pixoff = 2;

            // 填充的内容转化为字节数
            byte[] d = str.getBytes("utf-8"); // 设置编码方式
            if (d.length > 0 && d.length < 120) {
                boolean[][] s = x.calQrcode(d);
                for (int i = 0; i < s.length; i++) {
                    for (int j = 0; j < s.length; j++) {
                        if (s[j][i]) {
                            // 验证码图片填充内容
                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            }
            // 结束写入
            gs.dispose();
            // 结束内存图片
            bufferedImage.flush();
            /*
             * 保存生成的二维码图片 第一先生成4位随机字母字符串,用于给生成的二维码命名 第二保存生成的二维码
             * (char)(int)(Math.random()*26+65) 随机生成一个大写字母
             * (char)(int)(Math.random()*26+97) 随机生成一个小写字母
             */
            System.out.println("生成的4位随机字符串为:");
            for (int i = 0; i < 4; i++) {
                char c = (char) (int) (Math.random() * 26 + 65);
                System.out.print(c);
            }
            ImageIO.write(bufferedImage, "png", new File("E:/erweima/1" + (char) (int) (Math.random() * 26 + 65)
                    + (char) (int) (Math.random() * 26 + 97) + ".png"));
            System.out.println("\n二维码图片生成成功!");
        }
    }
}

第三种



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

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.oned.CodaBarWriter;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.oned.Code39Writer;
import com.google.zxing.oned.EAN13Writer;
import com.google.zxing.oned.EAN8Writer;
import com.google.zxing.oned.ITFWriter;
import com.google.zxing.oned.UPCAWriter;
import com.google.zxing.pdf417.encoder.PDF417Writer;
import com.google.zxing.qrcode.QRCodeWriter;

/**
 * 利用zxing开源工具生成二维码QRCode
 * 
 * @date 2012-10-26
 * @author xhw
 * 
 */
public class QRCode {
    private static final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * @param args
     */
    public static void main(String[] args) {
        QRCode test = new QRCode();
        File file = new File("E://erweima/test.png");
       
        test.encode("http://www.cnblogs.com/hongten", file, BarcodeFormat.QR_CODE, 200, 200, null);
        test.decode(file);
    }

    /**
     * 生成QRCode二维码<br> 
     * 在编码时需要将com.google.zxing.qrcode.encoder.Encoder.java中的<br>
     *  static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br>
     *  修改为UTF-8,否则中文编译后解析不了<br>
     */
    public void encode(String contents, File file, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) {
        try {
                 //消除乱码
     contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1"); 
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width, height);
            writeToFile(bitMatrix, "png", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成二维码图片<br>
     * 
     * @param matrix
     * @param format图片格式
     * @param file 生成二维码图片位置
     * @throws IOException
     */
    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        ImageIO.write(image, format, file);
    }

    /**
     * 生成二维码内容<br> 
     * @param matrix
     * @return
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
            }
        }
        return image;
    }

    /**
     * 解析QRCode二维码
     */
    @SuppressWarnings("unchecked")
    public void decode(File file) {
        try {
            BufferedImage image;
            try {
                image = ImageIO.read(file);
                if (image == null) {
                    System.out.println("Could not decode image");
                }
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                Result result;
                @SuppressWarnings("rawtypes")
                Hashtable hints = new Hashtable();
                //解码设置编码方式为:utf-8
                hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
                result = new MultiFormatReader().decode(bitmap, hints);
                String resultStr = result.getText();
                System.out.println("解析后内容:" + resultStr);
            } catch (IOException ioe) {
                System.out.println(ioe.toString());
            } catch (ReaderException re) {
                System.out.println(re.toString());
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
    }
}

效果展示:

参考链接:

猜你喜欢

转载自blog.csdn.net/qq_38720976/article/details/84454805