😊 @ 作者: 一恍过去



java 二维码 乱码 java二维码解析_开发语言


目录

  • 前言
  • 1、POM
  • 2、普通二维码生成
  • 3、Logo二维码生成
  • 4、二维码解析
  • 5、完整代码


前言

二维码的图片的绘制主要是通过Graphics2DBufferedImage两个类进行实现。

  • BufferedImage:是Java中表示图像的类,它继承自Image类,并提供了对图像数据进行访问和操作的方法。它是基于内存的图像缓冲区,可以在内存中进行像素级别的图像处理。
  • Graphics2D:是Java中用于绘图和图形操作的2D图形渲染引擎。它是java.awt.Graphics类的子类,并提供了更丰富的功能和方法,用于处理2D图形对象、绘制图形和进行图形操作。

1、POM

<dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.5.0</version>
        </dependency>

2、普通二维码生成

工具类:

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成工具类
 */
public class QrCodeUtils {
    /**
     * 二维码尺寸
     */
    private static final int QRCODE_SIZE = 300;

    /**
     * 生成二维码
     *
     * @param url 二维码解析后的URL地址
     * @return 图片
     * @throws Exception
     */
    public static BufferedImage getQrLogoCode(String url) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<>(8);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 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) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        return image;
    }
}

实现类:

@RestController
@RequestMapping("/test")
@Slf4j
public class Controller {
    /**
     * 生成二维码
     *
     * @param response
     */
    @GetMapping(value = "/qr")
    public void getQrCodeImage(HttpServletResponse response) {
        try (OutputStream os = response.getOutputStream()) {
            String url = "https://www.baidu.com";
            // 生成二维码对象
            BufferedImage image = QrCodeUtils.getQrLogoCode(url);
            //设置response
            response.setContentType("image/png");
            // 输出jpg格式图片
            ImageIO.write(image, "jpg", os);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("二维码生成失败!");
        }
    }
}

测试:

地址:http://localhost:10010/test/qr

java 二维码 乱码 java二维码解析_开发语言_02

3、Logo二维码生成

工具类:

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
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.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成工具类
 */
public class QrCodeUtils {
    /**
     * 二维码尺寸
     */
    private static final int QRCODE_SIZE = 300;
    /**
     * LOGO宽度
     */
    private static final int LOGO_WIDTH = 80;
    /**
     * LOGO高度
     */
    private static final int LOGO_HEIGHT = 80;

    /**
     * 生成二维码
     *
     * @param url      二维码解析后的URL地址
     * @param logoPath logo地址 如果为空则表示不带logo
     * @return 图片
     * @throws Exception
     */
    public static BufferedImage getQrLogoCode(String url, String logoPath) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<>(8);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 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) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (logoPath == null || "".equals(logoPath)) {
            return image;
        }
        // 插入图片
        QrCodeUtils.setLogoImage(image, logoPath);
        return image;
    }

    /**
     * 插入LOGO
     *
     * @param source   二维码图片
     * @param logoPath LOGO图片地址
     * @throws IOException
     */
    private static void setLogoImage(BufferedImage source, String logoPath) throws Exception {
        Image imageIo = ImageIO.read(new File(logoPath));
        int width = imageIo.getWidth(null);
        int height = imageIo.getHeight(null);

        // 设置图片尺寸,如果超过指定大小,则进行响应的缩小
        if (width > LOGO_WIDTH || height > LOGO_HEIGHT) {
            width = LOGO_WIDTH;
            height = LOGO_HEIGHT;
        }

        Image image = imageIo.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        // 重新绘制Image对象
        g.drawImage(image, 0, 0, null);
        g.dispose();
        imageIo = image;

        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        // 设置为居中
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(imageIo, 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();
    }
}

实现类:

@RestController
@RequestMapping("/test")
@Slf4j
public class Controller {
    /**
     * 生成带logo的二维码
     *
     * @param response
     */
    @GetMapping(value = "/qr/logo")
    public void getQrLogoCodeImage(HttpServletResponse response) {
        try (OutputStream os = response.getOutputStream()) {
            String url = "https://www.baidu.com";
            String logoPath = "C:\\Users\\Desktop\\123.jpg";
            // 生成二维码对象
            BufferedImage image = QrCodeUtils.getQrLogoCode(url, logoPath);
            //设置response
            response.setContentType("image/png");
            // 输出jpg格式图片
            ImageIO.write(image, "jpg", os);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("二维码生成失败!");
        }
    }
}

测试:

地址:http://localhost:10010/test/qr

java 二维码 乱码 java二维码解析_开发语言_03

4、二维码解析

工具类:

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成工具类
 */
public class QrCodeUtils {

    /**
     * 解析二维码
     *
     * @param inputStream 二维码图片流
     * @return
     * @throws Exception
     */
    public static String decodeQrImage(InputStream inputStream) throws Exception {
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Map<DecodeHintType, Object> hints = new HashMap<>(2);
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }
}

实现类:

@RestController
@RequestMapping("/test")
@Slf4j
public class Controller {
    /**
     * 解析二维码图片,返回字符串
     *
     * @param file
     */
    @PostMapping(value = "/decode")
    public String decodeQrImage(@RequestParam("file") MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            return QrCodeUtils.decodeQrImage(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("二维码解析失败!");
        }
    }
}

测试:

使用PostMan进行测试,将生成的二维码上传,可以看到成功返回了url数据

java 二维码 乱码 java二维码解析_开发语言_04

5、完整代码

工具类:

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.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成工具类
 */
public class QrCodeUtils {
    /**
     * 二维码尺寸
     */
    private static final int QRCODE_SIZE = 300;
    /**
     * LOGO宽度
     */
    private static final int LOGO_WIDTH = 80;
    /**
     * LOGO高度
     */
    private static final int LOGO_HEIGHT = 80;

    /**
     * 生成二维码
     *
     * @param url      二维码解析后的URL地址
     * @param logoPath logo地址 如果为空则表示不带logo
     * @return 图片
     * @throws Exception
     */
    public static BufferedImage getQrLogoCode(String url, String logoPath) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<>(8);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 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) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (logoPath == null || "".equals(logoPath)) {
            return image;
        }
        // 插入图片
        QrCodeUtils.setLogoImage(image, logoPath);
        return image;
    }

    /**
     * 插入LOGO
     *
     * @param source   二维码图片
     * @param logoPath LOGO图片地址
     * @throws IOException
     */
    private static void setLogoImage(BufferedImage source, String logoPath) throws Exception {
        Image imageIo = ImageIO.read(new File(logoPath));
        int width = imageIo.getWidth(null);
        int height = imageIo.getHeight(null);

        // 设置图片尺寸,如果超过指定大小,则进行响应的缩小
        if (width > LOGO_WIDTH || height > LOGO_HEIGHT) {
            width = LOGO_WIDTH;
            height = LOGO_HEIGHT;
        }

        Image image = imageIo.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        // 重新绘制Image对象
        g.drawImage(image, 0, 0, null);
        g.dispose();
        imageIo = image;

        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        // 设置为居中
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(imageIo, 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 inputStream 二维码图片流
     * @return
     * @throws Exception
     */
    public static String decodeQrImage(InputStream inputStream) throws Exception {
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Map<DecodeHintType, Object> hints = new HashMap<>(2);
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }
}

实现类:

@RestController
@RequestMapping("/test")
@Slf4j
public class Controller {

    /**
     * 生成二维码
     *
     * @param response
     */
    @GetMapping(value = "/qr")
    public void getQrCodeImage(HttpServletResponse response) {
        try (OutputStream os = response.getOutputStream()) {
            String url = "https://www.baidu.com";
            // 生成二维码对象
            BufferedImage image = QrCodeUtils.getQrLogoCode(url, null);
            //设置response
            response.setContentType("image/png");
            // 输出jpg格式图片
            ImageIO.write(image, "jpg", os);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("二维码生成失败!");
        }
    }


    /**
     * 生成带logo的二维码
     *
     * @param response
     */
    @GetMapping(value = "/qr/logo")
    public void getQrLogoCodeImage(HttpServletResponse response) {
        try (OutputStream os = response.getOutputStream()) {
            String url = "https://www.baidu.com";
            String logoPath = "C:\\Users\\LiGezZ\\Desktop\\123.jpg";
            // 生成二维码对象
            BufferedImage image = QrCodeUtils.getQrLogoCode(url, logoPath);
            //设置response
            response.setContentType("image/png");
            // 输出jpg格式图片
            ImageIO.write(image, "jpg", os);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("二维码生成失败!");
        }
    }

    /**
     * 解析二维码图片,返回字符串
     *
     * @param file
     */
    @PostMapping(value = "/decode")
    public String decodeQrImage(@RequestParam("file") MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            return QrCodeUtils.decodeQrImage(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("二维码解析失败!");
        }
    }
}