• java-二维码生成页面输出


    二维码现在很流行。

    前端也有二维码的生成方式: jquery.qrcode

    qrcode其实是通过使用jQuery实现图形渲染,支持Html5技术的才能实现,只要是canvas实现的。传输门

    而java生成二维码已经很成熟了,兼容性也很好。

    直接下载jar包  传输门

    下载文件里有core-3.0.0.jar和BASE64Encoder.jar两个jar包

    第一个是二维码使用的,第二个是base64使用的

    不转换base64可以不使用第二个

    导入到项目中使用就可以了。

    基础使用方法:

    public String generalQRCode(String url){
              Hashtable hints= new Hashtable(); 
              hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 
              String binary = null;
              try {
            //400,400是二维码图片宽高 BitMatrix bitMatrix
    = new MultiFormatWriter().encode( url, BarcodeFormat.QR_CODE, 400, 400, hints); // 实现一: 输出图片到指定目录 // File outputFile = new File("d://1.jpg"); // MatrixToImageWriter.writeToFile(bitMatrix, "png", outputFile); // 实现二:生成二维码图片并将图片转为二进制传递给前台 // 1、读取文件转换为字节数组 ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedImage image = toBufferedImage(bitMatrix); //// ImageIO.write(image, "png", out); byte[] bytes = out.toByteArray(); // 2、将字节数组转为二进制 BASE64Encoder encoder = new BASE64Encoder(); binary = encoder.encodeBuffer(bytes).trim(); } catch (Exception e) { e.printStackTrace(); } return "data:image/png;base64,"+binary; } 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 < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } return image; }

    导包后直接复制到项目中就可以使用了。

    如果是springMVC框架,直接给generalQRCode方法加注解放到Controller里就可在前端调用了。

    如注解例子:

    @RequestMapping("/generalQRCode.do")

    @ResponseBody

  • 相关阅读:
    前端大文件分片上传/多线程上传
    网页大文件分片上传/多线程上传
    docker基础入门之二
    linux之iptable
    linux内核之网络协议栈
    ubuntu之iptables
    c++栈管理库TCMalloc、jeMalloc
    curl之post提交xml
    ceph基本操作整理
    docker基础入门之一
  • 原文地址:https://www.cnblogs.com/zhangzhicheng/p/7215076.html
Copyright © 2020-2023  润新知