分享6:绘制二维码/二维条码(java版)

最近客户抽筋了,不想要我们现有的二维码,转而采用二维条码。(这之前二维码也不是我做的)既然是甲方bb提出的,老板又安排到到我手上了,那么我就得心(一)甘(脸)情(苦)愿(逼)的默默解决呗。

二维码/二维条码介绍:http://www.systron.com.cn/2.htm
一维条码与二维条码区别:https://jingyan.baidu.com/article/7f766daf45f29d4100e1d079.html

JAVA版

效果图:
在这里插入图片描述


依赖jar:链接:https://pan.baidu.com/s/1vMXbaU_JslF33U5fY-MaxQ 提取码:27jh

import com.google.zxing.*;
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;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * @program: gzga0912
 * @description: 二维码工具
 * @author: cc2018
 * @create: 2019-10-21 10:38
 **/
public class QRCodeUtil {
    public static final String DIVISION="#";
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    private static final Integer POINTCOLOR = 0x00000000;
    private static final Integer QRBACKCOLOR = 0xFFFFFFFF;
    private static final int QRCODE_SIZE = 300;// 二维码尺寸
    private static final int LOGO_WIDTH = 60;  // logo宽度
    private static final int LOGO_HEIGHT = 60; // logo高度

    /**
     * 生成二维码图片流
     * @param content 二维码内容
     * @param imgPath 二维码中插入的图片
     * @param insertLogoCompress 插入logo是否压缩
     * @return 返回图片流程
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String imgPath, boolean insertLogoCompress) throws Exception {
        BufferedImage image = createImage(content);
        if (imgPath == null || "".equals(imgPath)) { return image;}
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, insertLogoCompress);
        return image;
    }

    /**
     * 生成二维码
     * @param content 二维码内容
     * @return 返回二维码图片流
     * @throws Exception
     */
    private static BufferedImage createImage(String content) throws Exception{
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE,//条形码格式  QR_CODE二维码  PDF_417条形码
                QRCODE_SIZE,//条码宽度
                QRCODE_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) ? POINTCOLOR : QRBACKCOLOR);
            }
        }
        return image;
    }

    /**
     * 插入图片到二维码中
     * @param source
     * @param imgPath 插入二维码中的图片
     * @param insertLogoCompress 是否需要压缩插入的图片
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean insertLogoCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        //提供read()和write()静态方法,读写图片
        Image src = ImageIO.read(new File(imgPath));//读取需要插入的文件为图片类型
        int width = src.getWidth(null);//获取插入的图片宽度
        int height = src.getHeight(null);//获取插入的图片高度
        if (insertLogoCompress) { // 压缩LOGO
            if (width > LOGO_WIDTH) {width = LOGO_WIDTH; }
            if (height > LOGO_HEIGHT) {height = LOGO_HEIGHT;}
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();//在二维码流中插入logo
        int startX = (QRCODE_SIZE - width) / 2;//logo插入startX起始坐标  width结束x坐标
        int startY = (QRCODE_SIZE - height) / 2;//logo插入startY起始坐标 height结束y坐标
        graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));// 1.0f为透明度 ,值从0-1.0,依次变得不透明
        graph.drawImage(src, startX, startY, width, height, null);
        graph.setStroke(new BasicStroke(1f));//设置线条宽度
        Shape shape = new RoundRectangle2D.Float(startX, startY, width, height, 6, 6);
        graph.draw(shape);
        graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));//结束透明设置
        graph.dispose();
    }

    /**
     * 生成二维码
     * @param content 二维码内容
     * @param imgPath 二维码插入图片
     * @param destPath 二维码生成存放路径
     * @param insertLogoCompress 是否需要压缩插入的图片
     * @throws Exception
     */
    public static void encode(String content, String imgPath, String destPath, boolean insertLogoCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, insertLogoCompress);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static void encode(String content, String destPath) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static void encode(Map<String, String> content, String destPath) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(getStrByMap(content));
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    /**
     * 通过给定的路径生成文件
     * @param destPath
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 解析二维码
     * @param file 二维码文件
     * @return 返回二维码得到的字符串结果集
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二维码
     * @param path 二维码路径
     * @return
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QRCodeUtil.decode(new File(path));
    }

    public static void main(String[] args) throws Exception {
        // 存放在二维码中的内容
        Map<String, String> map = new HashMap<>();
        map.put("name", "cc百川");
        map.put("data", "2019-10-25");
        // 嵌入二维码的图片路径
        String imgPath = "D:/qc/sourceimg/1.jpg";
        // 生成的二维码的路径及名称
        String destPath = "D:/qc/cctest1021.jpg";
        //生成二维码
        QRCodeUtil.encode(getStrByMap(map), imgPath, destPath, true);
//        QRCodeUtil.encode(map, destPath);
        // 解析二维码
        String str = QRCodeUtil.decode(destPath);
        String [] returns = str.split(QRCodeUtil.DIVISION);
        System.out.println(Arrays.toString(returns));
        // 打印出解析出的内容
        System.out.println(str);

    }

    public static String getStrByMap(Map<String, String> data) {
        String str = "";
        if(data == null || data.isEmpty()) return str;

        for(Map.Entry<String, String> ent : data.entrySet()){
           str += ent.getKey()+"="+ent.getValue() +DIVISION;
        }
        return str;
    }

}

注意点:

1.设置背景透明

Graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));// 1.0f为透明度 ,值从0-1.0,依次变得不透明
xxxx
Graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));//结束透明设置

2.设置二维码图片中插入logo

Graphics2D graph = source.createGraphics();//source二维码流
Image src = ImageIO.read(new File(imgPath));//读取需要插入的文件为图片类型
graph.drawImage(src, startX, startY, width, height, null);
xxx

3.插入边框

 	graph.setStroke(new BasicStroke(1f));//设置线条宽度
    Shape shape = new RoundRectangle2D.Float(startX, startY, width, height, 6, 6);
    graph.draw(shape)

4.二维码点整颜色设置

 		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) ? 0x00000000: 0xFF00FFFF);
            }
        }

5.设置二维码扫描后直接跳转路径

内容直接写你想要跳转后的路径
	BitMatrix bitMatrix = new MultiFormatWriter().encode("http://www.baidu.com",
                BarcodeFormat.QR_CODE,//条形码格式  QR_CODE二维码  PDF_417条形码
                QRCODE_SIZE,//条码宽度
                QRCODE_SIZE,//条码高度
                hints//条码其他参数
        );

6.生成二维条码

BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.PDF_417,//条形码格式  QR_CODE二维码  PDF_417条形码
                QRCODE_SIZE,//条码宽度
                QRCODE_SIZE,//条码高度
                hints//条码其他参数
        );

7.解码,利用MultiFormatReader类

 		Result result;
 	    Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);

畅想:我们就可以利用二维码扫码登录了,我想的方案是利用WebSocket进行双工通信,或者利用Redis发布订阅。

以上是本周开发中稍微有趣的东西,望大家多多指教。

发布了55 篇原创文章 · 获赞 29 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/ljcc122/article/details/102742978