Java实现生成二维码(含logo)

目  录

1、创建项目并配置Maven和添加依赖

2、谷歌帮助类

3、工具类

4、主类

5、运行生成二维码


1、创建项目并配置Maven和添加依赖

新建一个项目QRCodeDemo,配置好maven仓库后,在项目的pom.xml中添加依赖:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ljh</groupId>
    <artifactId>testDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <target>9</target>
                    <source>9</source>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2、谷歌帮助类

在项目文件夹下新建一个帮助类,类名为:BufferedImageLuminanceSource.java,这是谷歌提供的帮助类,导入包com.google.zxing.LuminanceSource即可使用。

BufferedImageLuminanceSource.java

package com.ljh.QRCode.utils;

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);
    }
}

3、工具类

新建一个工具类:QRCodeUtil.java,设置生成的二维码的图片的名字。

QRCodeUtil.java

package com.ljh.QRCode.utils;

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.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

public class QRCodeUtil {
    private static final String CHARSET = "utf-8";
    private static final String IMG_FORMAT_NAME = "PNG";

    private static final Integer QR_CODE_SIZE = 300;
    private static final Integer WIDTH = 60;
    private static final Integer HEIGHT = 60;

    private static BufferedImage createImage(String content, String imgPath, Boolean needCompress) throws WriterException, IOException {

        Hashtable<EncodeHintType, Object> ht = new Hashtable<EncodeHintType, Object>();
        ht.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        ht.put(EncodeHintType.CHARACTER_SET, CHARSET);
        ht.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, ht);
        int height = bitMatrix.getHeight();
        int width = bitMatrix.getWidth();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                image.setRGB(i, j, bitMatrix.get(i,j) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        if (imgPath == null || "".equals(imgPath)) {
            return image;
        }

        QRCodeUtil.insertImg(image, imgPath, needCompress);

        return image;
    }

    private static void insertImg(BufferedImage source, String imgPath, Boolean needCompress) throws IOException {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            throw new FileNotFoundException();
        }

        Image src = ImageIO.read(file);
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) {
            if (width > WIDTH) width = WIDTH;
            if (height > WIDTH) height = WIDTH;
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = img.createGraphics();
            g.dispose();
            src = image;
        }

        Graphics2D graph = source.createGraphics();
        int x = (QR_CODE_SIZE - width) / 2;
        int y = (QR_CODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    public static void encode(String content, String imgPath, String destPath, Boolean needCompress) throws IOException, WriterException, ClassNotFoundException {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdir(destPath);

        ImageIO.write(image, IMG_FORMAT_NAME, new File(destPath));
    }

    public static BufferedImage encode(String content, String imgPath, Boolean needCompress) throws IOException, WriterException, ClassNotFoundException {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        return image;
    }

    public static void encode(String content, String imgPath, OutputStream outputStream, Boolean needCompress) throws IOException, WriterException, ClassNotFoundException {
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, IMG_FORMAT_NAME, outputStream);
    }

    public static void encode(String content, String destPath) throws ClassNotFoundException, IOException, WriterException {
        QRCodeUtil.encode(content, null, destPath, false);
    }

    public static void encode(String content, OutputStream outputStream) throws ClassNotFoundException, IOException, WriterException {
        QRCodeUtil.encode(content, null, outputStream, false);
    }

    public static String decode(File file) throws IOException, NotFoundException {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            throw new IOException();
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> ht = new Hashtable<DecodeHintType, Object>();
        ht.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, ht);
        return result.getText();
    }

    public static String decode(String path) throws IOException, NotFoundException {
        return QRCodeUtil.decode(new File(path));
    }

    private static void mkdir(String destPath) {
        File file = new File(destPath);

        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }
}

4、主类

在test文件夹下新建一个主类:QRCodeUtilTest

QRCodeUtilTest.java

package com.ljh.QRCode.utils;


import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import org.junit.Test;

import java.io.File;
import java.io.IOException;


public class QRCodeUtilTest {
    @Test
    public void QRCodeTest() {
        String text = "Java实现生成二维码(含logo)!";
        String path = this.getClass().getResource("/").getPath();
        String imgPath = path + "idea1.jpg";
        String destPath = "test.png";
        try {
            QRCodeUtil.encode(text, imgPath, destPath, true);
        } catch (IOException | WriterException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {
            String str = QRCodeUtil.decode(destPath);
            System.out.println(str);
        } catch (IOException | NotFoundException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void filePathTest() {
        File file = new File("idea1.jpg");
        System.out.println(file.getAbsolutePath());
    }

}

字段解释:

QRCodeUtil.encode(text, imgPath, destPath, true)语句中:

text:编码到二维码中的内容,例如:“Java实现生成二维码(含logo)!”;

imgPath:指嵌入二维码的图片路径,如果不写或者为null则生成的二维码没有logo;

destPath:二维码生成的存放路径;

true:指把logo进行压缩,也可以设置为“false”则不进行压缩;

QRCodeUtil.decode(destPath)语句中:

destPath:指要解析的二维码的存放路径,其返回值为String类型,即返回解析出后的内容。
 

5、运行生成二维码

在src\test\resources\添加图片idea1.jpg

在String text = " ";中输入Java实现生成二维码(含logo)!

运行QRCodeUtilTest类

生成的在二维码为test.png

识别生成的二维码进行解析:

 

 如需更换二维码的logo和解析后的文本内容,只需修改如下几个地方即可

 

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java生成二维码并保存图片的示例代码: ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class QRCodeGenerator { public static void main(String[] args) { String text = "https://www.csdn.net"; int width = 500; int height = 500; String format = "jpg"; String filePath = "d://test//out.jpg"; String logoPath = "E:\\test.jpg"; try { QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } File qrFile = new File(filePath); ImageIO.write(bufferedImage, format, qrFile); if (logoPath != null && !"".equals(logoPath.trim())) { QRCodeUtil.addLogo(qrFile, new File(logoPath), new LogoConfig()); } } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 其中,QRCodeUtil是一个工具类,用于在二维码中添加Logo。你可以在这里找到QRCodeUtil的完整代码:https://github.com/liuyueyi/quick-media/blob/master/quick-media/src/main/java/com/github/hui/quick/plugin/qrcode/util/QRCodeUtil.java
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值