java生成二维码和解析二维码


  前阵子忽然对生成自定义内容的二维码感兴趣,于是上网查,了解到谷歌提供了二维码生成和解析的jar包。然后还看到了一篇大佬的博文《 java实现二维码的生成与解析 - jam_fanatic》,大佬贴的代码结合找好的jar包,可以直接使用。这里我copy过来作为学习笔记,若觉得有用,记得给大佬博文点赞~


jar包下载地址

https://mvnrepository.com/artifact/com.google.zxing/core
在这里插入图片描述
在这里插入图片描述


代码

代码类名及结构

需要的几个类

谷歌类:BufferedImageLuminanceSource

  这个类是谷歌提供的帮助类 (小声:我直接从大佬博文里copy的)

package QRcode;

import com.google.zxing.LuminanceSource;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

public class BufferedImageLuminanceSource extends LuminanceSource {

    private final BufferedImage image;
    private final int left;
    private final int top;

    public BufferedImageLuminanceSource(BufferedImage image) {
        this(image, 0, 0, image.getWidth(), image.getHeight());
    }

    public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
        super(width, height);

        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        if (left + width > sourceWidth || top + height > sourceHeight) {
            throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
        }

        for (int y = top; y < top + height; y++) {
            for (int x = left; x < left + width; x++) {
                if ((image.getRGB(x, y) & 0xFF000000) == 0) {
                    image.setRGB(x, y, 0xFFFFFFFF); // = white
                }
            }
        }

        this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
        this.image.getGraphics().drawImage(image, 0, 0, null);
        this.left = left;
        this.top = top;
    }

    public byte[] getRow(int y, byte[] row) {
        if (y < 0 || y >= getHeight()) {
            throw new IllegalArgumentException("Requested row is outside the image: " + y);
        }
        int width = getWidth();
        if (row == null || row.length < width) {
            row = new byte[width];
        }
        image.getRaster().getDataElements(left, top + y, width, 1, row);
        return row;
    }

    public byte[] getMatrix() {
        int width = getWidth();
        int height = getHeight();
        int area = width * height;
        byte[] matrix = new byte[area];
        image.getRaster().getDataElements(left, top, width, height, matrix);
        return matrix;
    }

    public boolean isCropSupported() {
        return true;
    }

    public LuminanceSource crop(int left, int top, int width, int height) {
        return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
    }

    public boolean isRotateSupported() {
        return true;
    }

    public LuminanceSource rotateCounterClockwise() {
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
        BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();
        int width = getWidth();
        return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
    }

}

工具类:QRCodeUtil

  在大佬写的工具类的基础上改成了我自己喜欢的代码风格,不过改着改着就有蛮多不一样了。。。

package QRcode;


import com.google.zxing.*;
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.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.Hashtable;

public class QRCodeUtil {
    //默认参数
    /** 字符的编码 */
    private static String charset = "utf-8";
    /** 二维码图片的格式 */
    private static String formatName = "JPG";
    /** 二维码尺寸 */
    private static int qrcodeSize = 300;
    /** LOGO宽度 */
    private static int width = 60;
    /** LOGO高度 */
    private static int height = 60;


/* ============================================= getter and setter method ============================================= */
	//修改参数
    public static void setCharset(String charset) {
        QRCodeUtil.charset = charset;
    }

    public static void setFormatName(String formatName) {
        QRCodeUtil.formatName = formatName;
    }

    public static void setQrcodeSize(int qrcodeSize) {
        QRCodeUtil.qrcodeSize = qrcodeSize;
    }

    public static void setWidth(int width) {
        QRCodeUtil.width = width;
    }

    public static void setHeight(int height) {
        QRCodeUtil.height = height;
    }
    
    public static String getCharset() {
        return charset;
    }

    public static String getFormatName() {
        return formatName;
    }

    public static int getQrcodeSize() {
        return qrcodeSize;
    }

    public static int getWidth() {
        return width;
    }

    public static int getHeight() {
        return height;
    }

/* ============================================= other method ============================================= */
    /**
     * 新建二维码图片缓存对象
     * @param content 需要编码的内容
     * @return
     * @throws Exception
     */
    public 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, qrcodeSize, qrcodeSize, 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) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    /**
     * 二维码中心插入logo图片
     * @param source
     * @param imgPath
     * @param needCompress
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > QRCodeUtil.width) {
                width = QRCodeUtil.width;
            }
            if (height > QRCodeUtil.height) {
                height = QRCodeUtil.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();
        int x = (qrcodeSize - width) / 2;
        int y = (qrcodeSize - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码图片
     * @param content
     * @param destPath
     * @throws Exception
     */
    public static void encode(String content, String destPath) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content);
        mkdirs(destPath);
        ImageIO.write(image, formatName, new File(destPath));
    }

    /**
     * 生成带中心Logo的二维码图片
     * @param content 需要存储的字符串内容
     * @param destPath 二维码图片存储路径
     * @param logoPath 需要嵌入中心的图片
     * @param needCompress 嵌入中心的图片是否需要压缩
     * @throws Exception
     */
    public static void encode(String content, String destPath,  String logoPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content);
        mkdirs(destPath);
        if (logoPath == null || "".equals(logoPath)) {
            System.out.println("未检测到Logo图片,将生成不带logo的二维码图片...");
        }else{
            // 插入logo图片
            QRCodeUtil.insertImage(image, logoPath, needCompress);
        }
        ImageIO.write(image, formatName, new File(destPath));
    }


    /**
     * 将二维码图片写入到指定输出流中
     * @param content 需要存储的字符串内容
     * @param output 指定输出流中
     * @throws Exception
     */
    public static void encode(String content, OutputStream output) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content);
        ImageIO.write(image, formatName, output);
    }

    /**
     * 将带logo的二维码图片写入到指定输出流中
     * @param content 需要存储的字符串内容
     * @param output 指定输出流中
     * @param logoPath logo的存放路径
     * @param needCompress logo图片是否需要压缩
     * @throws Exception
     */
    public static void encode(String content, OutputStream output, String logoPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content);
        if (logoPath == null || "".equals(logoPath)) {
            System.out.println("未检测到Logo图片,将创建不带logo的二维码图片对象...");
        }else{
            // 插入logo图片
            QRCodeUtil.insertImage(image, logoPath, needCompress);
        }
        ImageIO.write(image, formatName, output);
    }

    /**
     * <P>当文件夹不存在时,mkdirs会自动创建多层目录 </P>
     * <P> · 区别于mkdir,mkdir如果父目录不存在则会抛出异常 </P>
     * @param destPath
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        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) {
            System.out.println("未识别到该二维码图片文件");
            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 netPath 图片的网络地址
     * @return
     */
    public static String decode(URI netPath) throws Exception {
        //todo 从网络地址下载,保存到本地再解析的。还在想能否直接从流对象中识别解析二维码
        File netImageFile = null;
        InputStream inputStream = null;
        URL url = netPath.toURL();
        HttpURLConnection netConn = (HttpURLConnection) url.openConnection();
        //设置连接超时时间,单位毫秒(ms)
        netConn.setConnectTimeout(5*1000);
        //设置返回数据超时时间,单位毫秒(ms)
        netConn.setReadTimeout(5*1000);
        int httpStatus = netConn.getResponseCode();
        if (HttpURLConnection.HTTP_OK == httpStatus){
            FileOutputStream fileOutputStream = new FileOutputStream("D:/QRcode.jpg");
            inputStream = netConn.getInputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while((len=inputStream.read(b))!=-1){
                fileOutputStream.write(b,0,len);
            }
//            byte[] imageBytes = outStream.toByteArray();
            netImageFile = new File("D:/QRcode.jpg");
            inputStream.close();
            fileOutputStream.close();
        }else{
            System.out.println("未能获取到网络中的二维码,请稍后再试...");
        }
        // todo 获取网络二维码图片的File对象
        String result = decode(netImageFile);
        System.out.println(result);
        return null;
    }

    /**
     * 识别本地或网络中的二维码图片 - 未完成
     * @param path
     * @return
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        // todo 自动判断是网络连接还是本地地址,再根据情况解析
        return null;
    }

}

试验类:Test

package QRcode;

import java.net.URI;

public class Test {
    public static void main(String[] args) throws Exception {
        // 存放在二维码中的内容
        String text = "这里是Mr_door的博客 ~ ";
        // 二维码中心logo图片的路径
        String logoPath = "";//不放图片
        // 生成的二维码的路径及名称
        String destPath = "D:\\第一个二维码.jpg";
        //生成二维码
        QRCodeUtil.encode(text, destPath);
        // 解析这个二维码
        String str = QRCodeUtil.decode(destPath);
        // 打印出解析出的内容
        System.out.println(str);
    }
}

运行结果

1、生成了二维码,可以直接使用手机浏览器扫码查看内容。
在这里插入图片描述
2、控制台打印出了解析结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
生成二维码并将其保存到数据库中,您可以使用以下步骤: 1. 导入相关的Java库:您可以使用ZXing库来生成二维码。请确保已将其添加到您的Java项目中。 2. 生成二维码:使用ZXing库中的QRCodeWriter类,您可以创建一个QRCode对象,该对象可以转换为图片格式并保存到本地。 3. 将二维码图片转换为字节数组:使用ImageIO类将二维码图片转换为字节数组。 4. 将字节数组保存到数据库:使用JDBC连接到您的数据库,并使用PreparedStatement类将字节数组保存到数据库中。 以下是一些示例代码来演示这些步骤: ```java import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Base64; import javax.imageio.ImageIO; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class QRCodeGenerator { public static void main(String[] args) throws SQLException { String data = "Hello, world!"; // 数据内容 int size = 300; // 生成二维码图片大小 String format = "png"; // 二维码图片格式 byte[] imageBytes = null; // 生成二维码 QRCodeWriter writer = new QRCodeWriter(); BitMatrix matrix; try { matrix = writer.encode(data, com.google.zxing.BarcodeFormat.QR_CODE, size, size); BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, format, baos); imageBytes = baos.toByteArray(); } catch (WriterException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // 将字节数组保存到数据库 Connection conn = null; // 假设您已连接到数据库 PreparedStatement ps = conn.prepareStatement("INSERT INTO qr_codes (data) VALUES (?)"); ps.setBytes(1, imageBytes); ps.executeUpdate(); } } ``` 在这个示例中,我们生成一个包含字符串“Hello, world!”的二维码,将其转换为PNG格式的图片,将图片字节数组保存到名为“qr_codes”的数据库表中。请注意,此示例仅用于演示目的,您需要根据您的具体需求进行适当的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值