使用qr生成二维码

  最近有个需求是在页面为当前数据生成二维码。

  因为是以Java为开发语言,所以我选择了QRCode.jar这个第三方插件,首先下载qrcode.jar这个包,然后写一个生成二维码的工具类,这个类是参照别人的,更具需求修改了参数,代码如下:

public class EncodeUtil {
    private static final long serialVersionUID = 1L;
    public static byte[] createImage(String content) throws UnsupportedEncodingException {
        Qrcode qrcode = new Qrcode();
        qrcode.setQrcodeErrorCorrect('M');
        qrcode.setQrcodeEncodeMode('B');
        qrcode.setQrcodeVersion(15);
        //content为需要生成的字符串,可通过请求传入参数
        byte[] bstr = content.getBytes("UTF-8");
        BufferedImage bi = new BufferedImage(178, 178, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setBackground(Color.WHITE);   //背景颜色
        g.clearRect(0, 0, 178, 178);
        g.setColor(Color.BLACK);    //条码颜色
        System.out.println(bstr.length);
        if (bstr.length > 0 && bstr.length < 500) {
            boolean[][] b = qrcode.calQrcode(bstr);
            for (int i = 0; i < b.length; i++) {
                for (int j = 0; j < b.length; j++) {
                    if (b[j][i]) {
                        g.fillRect(j * 2 + 2, i * 2 + 2, 2, 2);
                    }
                }
            }
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
        try {
            encoder.encode(bi);
        } catch (ImageFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return os.toByteArray();
    }
}

这里特别注意一下自己的需求,在我的需求中二维码的数据会是300左右的字节,所以对

qrcode.setQrcodeVersion(15)进行了对应的设置,因为网上的讲解不是很全面很多,我也是测试了好几次才把这个参数设置得满足我的需求,下面的参数设置我没怎么修改,请自行搜索。
然后是调用这个工具类:
public class Test {


    private InputStream inputStream;

    public InputStream encode(){
        
        byte[] image = new byte[1024];
       
        try {
            image= EncodeUtil.createImage("test");
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        this.inputStream = new ByteArrayInputStream(image);
        return inputStream;
    }
}

这里是返回的数据流,直接返回会在新的页面返回二维码,而我的需求是将二维码以弹出框的形式弹出,所以这里我使用了模态框;

点击按钮,调用触发模态框的函数:

$("#mymodle").modal('show');
然后在模态框的主体内直接
<img src="××.do/>" style="position:absolute;top: 40%;left: 50%"/>
触发后台生成二维码,返回二维码数据流直接在模态框显示。



原文地址:https://www.cnblogs.com/yeleia/p/8603708.html