依赖

  <!--二维码-->
  <dependency>
     <groupId>com.google.zxing</groupId>
     <artifactId>core</artifactId>
     <version>3.4.1</version>
  </dependency>
xml

请求调用

 @GetMapping("/qr-code")
    public void qrCodeText(@RequestParam("text") String text, HttpServletResponse response, HttpServletRequest request) {
        try{
            byte[] bytes = QrCodeUtils.encodeQRCode(text);
            response.setContentType(QrCodeUtils.RESPONSE_CONTENT_TYPE);
            OutputStream stream = response.getOutputStream();
            stream.write(bytes);
            stream.flush();
        }catch (Exception e){
	    log.info("出错了");
        }
    }
java

二维码生成工具类

package com.lb.upload.fileupload.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
public class QrCodeUtils {

    public static int QRCODE_SIZE = 400;
    public static final String format = "png";
    public static final String RESPONSE_CONTENT_TYPE = "image/png";


    public static byte[] encodeQRCode(String text) {
        try {
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //容错率越高,可存储的信息越少;但是对二维码清晰对要求越小
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
            //还可以设置logo之类的

            // 生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
            bitMatrix = deleteWhite(bitMatrix);
            BufferedImage bufferedImage = toBufferedImage(bitMatrix);
        
            File logoImg ;
            if (request.getServerName().equals("localhost")) {
	        //本地
                logoImg = new File("src/main/resources/logo.jpg");
            } else {
                //服务端
		logoImg = new File("/usr/app/logo.jpg");
            }
 	    //加logo
            bufferedImage = encodeImgLogo(bufferedImage, logoImg);
	    //透明背景
            bufferedImage = convert(bufferedImage);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, format, out);
            return out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final int BORDER_WIDTH = 0;

    public static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();

        int resWidth = rec[2] + BORDER_WIDTH;
        int resHeight = rec[3] + BORDER_WIDTH;
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = BORDER_WIDTH; i < resWidth; i++) {
            for (int j = BORDER_WIDTH; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1])) resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        int onColor = 0xFF000000;
        int offColor = 0x00ffffff;
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor);
            }
        }
        return image;
    }

    public static BufferedImage encodeImgLogo(BufferedImage qr_img, File logoImg) {
        BufferedImage twodimensioncode = null;
        try {
            if (!logoImg.isFile()) {
                System.out.println("输入非图片");
                return null;
            }
            //读取二维码图片
            twodimensioncode = qr_img;
            //获取画笔
            Graphics2D g = twodimensioncode.createGraphics();
            //读取logo图片
            BufferedImage logo = ImageIO.read(logoImg);
            //设置二维码大小,太大,会覆盖二维码,此处20%
            int logoWidth = logo.getWidth(null) > twodimensioncode.getWidth() / 5 ? (twodimensioncode.getWidth() / 5) : logo.getWidth(null);
            int logoHeight = logo.getHeight(null) > twodimensioncode.getHeight() / 5 ? (twodimensioncode.getHeight() / 5) : logo.getHeight(null);
            // 确定二维码的中心位置坐标,设置logo图片放置的位置
            int x = (twodimensioncode.getWidth() - logoWidth) / 2;
            int y = (twodimensioncode.getHeight() - logoHeight) / 2;
            //开始合并绘制图片
            g.drawImage(logo, x, y, logoWidth, logoHeight, null);
            g.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
            //logo边框大小
            g.setStroke(new BasicStroke(2));
            //logo边框颜色
            g.setColor(Color.WHITE);
            g.drawRect(x, y, logoWidth, logoHeight);
            g.dispose();
            logo.flush();
            twodimensioncode.flush();
        } catch (Exception e) {
            System.out.println("二维码绘制logo失败");
        }
        return twodimensioncode;
    }

    public static BufferedImage convert(BufferedImage QrImg) {
        BufferedImage image = QrImg;
        ImageIcon imageIcon = new ImageIcon(image);
        BufferedImage bufferedImage = new BufferedImage(
                imageIcon.getIconWidth(), imageIcon.getIconHeight(),
                BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
        g2D.drawImage(imageIcon.getImage(), 0, 0,
                imageIcon.getImageObserver());
        int alpha = 0;
        for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage
                .getHeight(); j1++) {
            for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage
                    .getWidth(); j2++) {
                int rgb = bufferedImage.getRGB(j2, j1);
                if (colorInRange(rgb))
                    alpha = 0;
                else
                    alpha = 255;
                rgb = (alpha << 24) | (rgb & 0x00ffffff);
                bufferedImage.setRGB(j2, j1, rgb);
            }
        }
        g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
        return bufferedImage;
    }

    public static boolean colorInRange(int color) {
        int red = (color & 0xff0000) >> 16;
        int green = (color & 0x00ff00) >> 8;
        int blue = (color & 0x0000ff);
        if (red >= color_range && green >= color_range && blue >= color_range)
            return true;
        return false;
    }

    public static int color_range = 210;
    public static Pattern pattern = Pattern.compile("[0-9]*");

    public static boolean isNo(String str) {
        return pattern.matcher(str).matches();
    }
}


java
打赏
  • 微信
  • 支付宝
评论
来发评论吧~
···

歌手: