本文共 1991 字,大约阅读时间需要 6 分钟。
一、java生成二维码
这里使用QRCode方式生成二维码
需要导入的jar包的网址:
生成二维码:http://www.swetake.com/qrcode/index-e.html 读取二维码:https://osdn.jp/projects/qrcode
因为这两个jar包的名字相同,所以导入工程时要重命名
代码如下
生成二维码:
public static void main(String[] args) throws IOException { Qrcode x=new Qrcode(); x.setQrcodeErrorCorrect('M'); //纠错等级,H,M,L,Q x.setQrcodeEncodeMode('B');//N 代表数字 A 代表a-Z B 代表其他字符 x.setQrcodeVersion(7); //版本 0-40 String qrData = "www.taobao.com"; byte[] d =qrData.getBytes(); //byte[] d =qrData.getBytes("gb2312"); 如果有汉字的话 int width = 67 + 12*(7-1); //二维码宽度高度的公式 int height = 67 + 12*(7-1); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gs = bufferedImage.createGraphics(); gs.setBackground(Color.WHITE); //设置背景颜色 gs.setColor(Color.BLACK); //设置二维码颜色 gs.clearRect(0, 0, width, height); int pixoff = 2;//偏移量,防止出错 if (d.length>0 && d.length <120){ boolean[][] s = x.calQrcode(d); for (int i=0;i读取二维码:
自定义类
public class MyQRCode implements QRCodeImage { //实现接口 BufferedImage bufferedImage; public MyQRCode(BufferedImage bufferedImage){ //自定义的构造方法 this.bufferedImage = bufferedImage; } public int getHeight() { return this.bufferedImage.getHeight(); //得到二维码的高度 } public int getPixel(int arg0, int arg1) { return this.bufferedImage.getRGB(arg0, arg1); } public int getWidth() { //得到二维码的宽度 return this.bufferedImage.getWidth(); } }读取二维码的类
public static void main(String []args) throws Exception{ File file = new File("F:"+File.separator+"a.png"); //二维码图片所在的路径 BufferedImage bufferedImage = ImageIO.read(file); QRCodeDecoder codeDecoder = new QRCodeDecoder(); //将二维码解码成byte数组,需要一个QRCodeImage类型的参数 //QRCodeImage是一个接口,所以我们需要自定义一个类并实现QRCodeImage接口 byte[] b = codeDecoder.decode(new MyQRCode(bufferedImage)); String s = new String(b,"gb2312"); System.out.println(s);//输出网址 }
二、JavaScript生成二维码
需要导入的javascript文件:jquery-qrcode-1.0.zip,这个文件的下载链接:https://github.com/jeromeetienne/jquery-qrcode,当然还需要引入jquery
源代码:
转载地址:http://mjcrj.baihongyu.com/