Java根据数据库内容生成二维码

两个工具类:

BufferedImageLuminanceSource
package com.demo.qrcode;

import com.google.zxing.LuminanceSource;

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

/**
 * 用于二维码的解析 Google提供
 */
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;ygetHeight()){
            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;
    }

    @Override
    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;
    }

    @Override
    public boolean isCropSupported() {
        return true;
    }

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

    @Override
    public boolean isRotateSupported() {
        return true;
    }

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

}
MatrixToImageWriter
package com.demo.qrcode;

import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 用于二维码的生成 Google提供
 */
public final class MatrixToImageWriter {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private MatrixToImageWriter(){}

    public static BufferedImage toBufferedImage(BitMatrix matrix){
        int width =matrix.getWidth();
        int height =matrix.getHeight();
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        for (int x=0;x

使用类中放置两个方法

private String generateQRCode(String text, int width, int height, String format) throws Exception {
        Hashtable hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        String pathName = "D:/Java/new.png";
        File file = new File(pathName);
        if (file.exists()) file.delete();
        File outputFile = new File(pathName);
        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
        return pathName;
    }

    /**
     * 解析指定路径下的二维码图片
     *
     * @param filePath 二维码图片路径
     * @return
     */
    private String parseQRCode(String filePath) {
        String content = "";
        try {
            File file = new File(filePath);
            BufferedImage image = ImageIO.read(file);
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            MultiFormatReader formatReader = new MultiFormatReader();
            Result result = formatReader.decode(binaryBitmap, hints);

            System.out.println("result 为:" + result.toString());
            System.out.println("resultFormat 为:" + result.getBarcodeFormat());
            System.out.println("resultText 为:" + result.getText());
            //设置返回值
            content = result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

调用生成

String text = "器材名:\n"+
                "可用次数:";
        int width = 200;    //二维码图片的宽
        int height = 200;   //二维码图片的高
        String format = "png";  //二维码图片的格式
        //生成二维码图片,并返回图片路径
        String pathName = generateQRCode(text, width, height, format);
        System.out.println("生成二维码的图片路径: " + pathName);
        String content = parseQRCode(pathName);
        System.out.println("解析出二维码的图片的内容为: " + content);

 如果需要实现图片预览,可以借鉴此篇博客,前端将application/pdf改为image/jpeg就行:

element获取后端数据流实现PDF文件的预览(开发小记)_Master-Tang的博客-CSDN博客后端代码:/** * @param response * @param archiveId 文件id * @param openStyle = inline 预览  =attachment 下载 * @throws Exception */ @GetMapping("arcDownload") public void arcDownload(HttpServletResponse response, String archiveId,https://blog.csdn.net/weixin_42078172/article/details/116467177?spm=1001.2014.3001.5501

你可能感兴趣的:(java,java,spring,boot)