前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java/JavaScript生成和解析二维码

Java/JavaScript生成和解析二维码

作者头像
浩Coding
发布2019-07-03 14:20:09
1.6K1
发布2019-07-03 14:20:09
举报
文章被收录于专栏:浩Coding浩Coding浩Coding

一 Java生成和解析二维码

生成和解析二维码需要用到第三方的包: QRCODE.jar

二维码如何实现不用关心,只需要了解下面两个方法。

生成二维码qrCodeEncode:把字符串写进二维码,并且生成图片到filePath。

public static void qrCodeEncode(String data, String filePath)

解析二维码qrCodeDecode:把二维码信息从imageFile中读取出来。

public static String qrCodeDecode(String imagePath) 

话不多说,直接上例子,将指定字符串:“微信搜索公众号:浩Coding”生成二维码到指定位置/home/hao/Desktop/1.png,再将其解析出来。

二维码生成工具类QRCodeUtil:

package QRCodeUtil;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

public class QRCodeUtil {

  /**
   * 把字符串写进二维码,并且生成图片到filePath
   * 
   * @param data
   *            二维码信息
   * @param destFile
   *            生成二维码图片的保存路径
   * @param logoPath
   *            二维码中央logo路径
   * @throws IOException
   */
  public static void qrCodeEncode(String data, String filePath) throws IOException {
    Qrcode qrcode = new Qrcode();
    qrcode.setQrcodeErrorCorrect('M'); // 纠错级别(L 7%、M 15%、Q 25%、H 30%)和版本有关
    qrcode.setQrcodeEncodeMode('B');
    qrcode.setQrcodeVersion(7); // 设置Qrcode包的版本

    byte[] d = data.getBytes("GBK"); // 字符集 如果出现中文扫描乱码情况,请更换UTF-8 字符集
    BufferedImage bi = new BufferedImage(139, 139, BufferedImage.TYPE_INT_RGB);
    // createGraphics // 创建图层
    Graphics2D g = bi.createGraphics();

    g.setBackground(Color.WHITE); // 设置背景颜色(白色)
    g.clearRect(0, 0, 139, 139); // 矩形 X、Y、width、height
    g.setColor(Color.BLACK); // 设置图像颜色(黑色)

    if (d.length > 0 && d.length < 123) {
      boolean[][] b = qrcode.calQrcode(d);
      for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < b.length; j++) {
          if (b[j][i]) {
            g.fillRect(j * 3 + 2, i * 3 + 2, 3, 3);
          }
        }
      }
    }

    //放置二维码中央logo,但是不易调节位置,且影响二维码识别率,故此注释
//    if (logoPath != null) {
//      Image img = ImageIO.read(new File(logoPath));
//      g.drawImage(img, 25, 55, 60, 50, null);
//    }
    
    g.dispose(); // 释放此图形的上下文以及它使用的所有系统资源。调用 dispose 之后,就不能再使用 Graphics 对象
    bi.flush(); // 刷新此 Image 对象正在使用的所有可重构的资源

    File qrFile = new File(filePath);
    ImageIO.write(bi, "png", qrFile);
    System.out.println("Input Encoded data is:" + data + "\n" + "Qr Code File Path:" + filePath);
  }

  /**
   * 解析二维码,返回解析内容
   * 
   * @param imagePath 二维码图片地址
   * @return
   */
  public static String qrCodeDecode(String imagePath) {
    String decodedData = null;
    QRCodeDecoder decoder = new QRCodeDecoder();
    BufferedImage image = null;
    try {
      image = ImageIO.read(new File(imagePath));
    } catch (IOException e) {
      System.out.println("Error: " + e.getMessage());
    }

    try {
      decodedData = new String(decoder.decode(new J2SEImage(image)), "GBK");
      // System.out.println("Output Decoded Data is:" + decodedData);
    } catch (DecodingFailedException dfe) {
      System.out.println("Error: " + dfe.getMessage());
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return decodedData;
  }

  // 继承了QRCodeImage类,读取一些图片数据
  static class J2SEImage implements QRCodeImage {
    BufferedImage image;

    public J2SEImage(BufferedImage image) {
      this.image = image;
    }

    public int getWidth() {
      return image.getWidth();
    }

    public int getHeight() {
      return image.getHeight();
    }

    public int getPixel(int x, int y) {
      return image.getRGB(x, y);
    }
  }

}

实例测试类QRCodeTest:

package QRCodeTest;

import java.io.IOException;

import QRCodeUtil.QRCodeUtil;

public class QRCodeTest {

  public static void main(String[] args) {
    // 二维码内容
    String data = "微信搜索公众号:浩Coding";
    String filePath = "/home/hao/Desktop/1.png";
//    String logoPath = "/home/hao/Desktop/logo.png";
    // File qrFile = new File(filePath);

    try {
//      QRCodeUtil.qrCodeEncode(data, filePath, logoPath);
      QRCodeUtil.qrCodeEncode(data, filePath);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // 解码
    String reText = QRCodeUtil.qrCodeDecode(filePath);
    System.out.println(reText);
  }

}

运行效果:

二 JavaScript生成和解析二维码

上面讲解了如何用Java生成和解析二维码, 这个知识点讲解如何用JavaScript创建二维码图片。 貌似JavaScript就不需要解析二维码图片了,没有应用场景,就不讲解析了。

首先需要第三方的js文件:jquery.qrcode.min.js,为了让它可以工作,还需要jquery的js。

用法很简单:

$('#qrcode').qrcode({render:'canvas',text:"微信搜索公众号:浩Coding",width:260,height:260});  

注: 其中的canvas还可以换成 table,用于在不支持html5的浏览器中使用。

效果:

附上全部代码:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<script src="js/jquery/2.0.0/jquery.min.js"></script>
<script src="js/qrcode/jquery.qrcode.min.js"></script>
</head> 

<div style="width:800px;margin:50px auto;text-align:center">
把字符串:&nbsp; 
<input type="text" name="textqr" id="textqr"/>
&nbsp;转换为二维码
<br/><br/>
<button type="button" onclick="qr()">点击生成二维码</button><br/><br/><br/>
<div id="qrcode"></div>
</div>

<script>
//生成二维码 其中的canvas还可以换成 table,用于在不支持html5的浏览器中使用。
function qr(){
  $('#qrcode').empty();
  var textqrStr = $('#textqr').val();
  textqrStr = utf16to8(textqrStr);
  //alert(textqrStr);
  $('#qrcode').qrcode({render:'canvas',text:textqrStr,width:260,height:260});  
}
//转码,用以显示中文。
function utf16to8(str) { 
    var out, i, len, c; 
    out = ""; 
    len = str.length; 
    for(i = 0; i < len; i++) { 
    c = str.charCodeAt(i); 
    if ((c >= 0x0001) && (c <= 0x007F)) { 
        out += str.charAt(i); 
    } else if (c > 0x07FF) { 
        out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); 
        out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F)); 
        out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F)); 
    } else { 
        out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F)); 
        out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F)); 
    } 
    } 
    return out; 
}
</script>
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 浩Coding 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档