Java生成、解析二维码方案以及代码实现(带Logo二维码生成)

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.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
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.InputStream;
import java.net.URL;
import java.net.URLConnection;
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图片地址
     */
    private static void setLogoImage(BufferedImage source, String logoPath) throws Exception {
        URL url = new URL(logoPath);
        URLConnection connection = url.openConnection();
        InputStream is = connection.getInputStream();

//        Image imageIo = ImageIO.read(new File(logoPath));
        Image imageIo = ImageIO.read(is);
        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();
    }


}

实现类:


import com.utils.QrCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/qrcode")
@Slf4j
public class QrCodeController {

    /**
     * 生成二维码
     *
     * @param response
     */
    @GetMapping(value = "/qrcode")
    public void getQrCodeImage(HttpServletResponse response) {
        try (OutputStream os = response.getOutputStream()) {
            String url = "http://timoa.cn";
            // 生成二维码对象
            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 = "/qrcode/logo")
    public void getQrLogoCodeImage(HttpServletResponse response) {
        try (OutputStream os = response.getOutputStream()) {
            String url = "http://timoa.cn";
            String logoPath = "http://timoa.cn/dist/images/logo/logo.png";
            // 生成二维码对象
            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("二维码解析失败!");
        }
    }


}

能够正常生成二维码(无logo及有logo),由于csdn会屏蔽,不放二维码图片了。

–end–

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值