二维码分为好多种,我们最常用的是qrcode类型的二维码,以下有三种生成方式以及解析方式:
附所需jar包或者js地址
第一种:依赖qrcode.jar
import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.UnsupportedEncodingException; import javax.imageio.ImageIO; import com.swetake.util.Qrcode; /**获取qrcode jar包 https://osdn.jp/projects/qrcode * 生成qrcode二维码 * @author fangyi * */ public class CreateQrCode { public static void main(String[] args) throws Exception { Qrcode qrcode= new Qrcode(); qrcode.setQrcodeErrorCorrect('M');//纠错等级 qrcode.setQrcodeEncodeMode('B');//N代表数字 A代表字母 B代表其他 qrcode.setQrcodeVersion(7);//版本 String qrData ="www.baidu.com";//二维码信息内容 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;//偏移量 byte[] d = qrData.getBytes("gb2312");//编码防止有中文 if (0 < d.length && d.length<120) { boolean[][] s = qrcode.calQrcode(d); for (int i = 0; i < s.length; i++) { for (int j = 0; j < s.length; j++) { if(s[j][i]){ gs.fillRect(i*3+pixoff, j*3+pixoff, 3, 3); } } } } //关闭资源,并保存文件 gs.dispose(); bufferedImage.flush(); ImageIO.write(bufferedImage, "png", new File("D:/qrcode.jpg"));//输出到指定地方 } }读取指定的二维码:
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import jp.sourceforge.qrcode.QRCodeDecoder; /** * 读取制定路径下的qrcode信息 * @author fangyi * */ public class ReaderQrcode { public static void main(String[] args) throws IOException { //指定的二维码文件路径 File file= new File("D:/jqueryqrcode.png"); BufferedImage bufferedImage = ImageIO.read(file); QRCodeDecoder qrCodeDecoder = new QRCodeDecoder(); String result = new String(qrCodeDecoder.decode(new MyQRCodeImage(bufferedImage)),"gb2312"); //输出结果 System.out.println(result); bufferedImage.flush(); } } import java.awt.image.BufferedImage; import jp.sourceforge.qrcode.data.QRCodeImage; /** * 自定义QRCodeImage类实现QRCodeImage 供读取时所用 * @author fangyi * */ public class MyQRCodeImage implements QRCodeImage { BufferedImage bufferedImage ; public MyQRCodeImage(BufferedImage bufferedImage) { super(); this.bufferedImage = bufferedImage; } @Override public int getHeight() { return bufferedImage.getHeight(); } @Override public int getPixel(int arg0, int arg1) { return bufferedImage.getRGB(arg0, arg1); } @Override public int getWidth() { return bufferedImage.getWidth(); } }第二种:创建动态的web工程 依赖jquery.qrcode.min.js jquery.js 运行工程访问下面jsp就可以了
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>生成二维码</title> <!-- js地址https://github.com/jeromeetienne/jquery-qrcode --> <script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.min.js"></script> <script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.qrcode.min.js"></script> </head> <body> 生成二维码如下:<br><br><br> <div id="qrcode"></div> <script type="text/javascript"> $('#qrcode').qrcode("www.baidu.com"); //生产二维码 /* jquery('#qrcode').qrcode({width: 64,height: 64,text: "size doesn't matter"}); */ </script> </body> </html>第三种 创建Java project 依赖zxing3.2.1.jar
import java.io.File; import java.io.IOException; import java.util.Hashtable; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /** * zxing jar包地址 https://github.com/Candy1575/QRcode * 依赖MatrixToImageWriter类 * @author fangyi * */ public class EncodeTest { public static void Encode_QR_CODE() throws IOException, WriterException{ String contents = "ZXing 二维码内容1234!"; // 二维码内容 int width = 430; // 二维码图片宽度 300 int height = 430; // 二维码图片高度300 String format = "gif";// 二维码的图片格式 gif Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); // 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%) hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 内容所使用字符集编码 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值 // hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值 hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数 BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,//要编码的内容 //编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D, //Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D, //MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION BarcodeFormat.QR_CODE, width, //条形码的宽度 height, //条形码的高度 hints);//生成条形码时的一些配置,此项可选 // 生成二维码 File outputFile = new File("D:" + File.separator + "mycode.gif");//指定输出路径 MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile); } public static void main(String[] args) throws Exception { try { Encode_QR_CODE(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import javax.imageio.ImageIO; import com.google.zxing.common.BitMatrix; /** * 二维码的生成需要借助MatrixToImageWriter类, * 该类是由Google提供的,可以将该类直接拷贝到源码中使用,当然你也可以自己写个 * 生产条形码的基类 依赖LogoConfig类 */ public 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 < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, (matrix.get(x, y) ? BLACK : WHITE)); // image.setRGB(x, y, (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB())); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); //设置logo图标 LogoConfig logoConfig = new LogoConfig(); image = logoConfig.LogoMatrix(image); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); }else{ System.out.println("图片生成成功!"); } } public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); //设置logo图标 LogoConfig logoConfig = new LogoConfig(); image = logoConfig.LogoMatrix(image); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } } import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /** * 二维码 添加自定义 logo图标 处理的方法, * 模仿微信自动生成二维码效果,有圆角边框,logo和二维码间有空白区,logo带有灰色边框 * @author fangyi * */ public class LogoConfig { /** * 设置 logo * @param matrixImage 源二维码图片 * @return 返回带有logo的二维码图片 * @throws IOException * @author Administrator sangwenhao */ public BufferedImage LogoMatrix(BufferedImage matrixImage) throws IOException{ /** * 读取二维码图片,并构建绘图对象 */ Graphics2D g2 = matrixImage.createGraphics(); int matrixWidth = matrixImage.getWidth(); int matrixHeigh = matrixImage.getHeight(); /** * 读取Logo图片 */ BufferedImage logo = ImageIO.read(new File("C:\\Users\\fangyi\\Pictures\\code-wallpaper-18.png")); //开始绘制图片 g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//绘制 BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); g2.setStroke(stroke);// 设置笔画对象 //指定弧度的圆角矩形 RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20); g2.setColor(Color.white); g2.draw(round);// 绘制圆弧矩形 //设置logo 有一道灰色边框 BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); g2.setStroke(stroke2);// 设置笔画对象 RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20); g2.setColor(new Color(128,128,128)); g2.draw(round2);// 绘制圆弧矩形 g2.dispose(); matrixImage.flush() ; return matrixImage ; } }读取二维码信息
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import com.google.zxing.Binarizer; import com.google.zxing.BinaryBitmap; import com.google.zxing.EncodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.NotFoundException; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitArray; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; /** * 读取zxing类型下的二维码信息 * @author fangyi * */ public class ReadQrCode_Zxing { @SuppressWarnings("unchecked") public static void main(String[] args) { try { MultiFormatReader formatReader = new MultiFormatReader(); //读取指定的二维码文件 File file= new File("D:\\mycode.gif"); BufferedImage bufferedImage =ImageIO.read(file); BinaryBitmap binaryBitmap= new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage))); //定义二维码参数 Map hints= new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); Result result = formatReader.decode(binaryBitmap, hints); //输出相关的二维码信息 System.out.println("解析结果"+result.toString()); System.out.println("二维码格式类型"+result.getBarcodeFormat()); System.out.println("二维码文本内容"+result.getText()); bufferedImage.flush(); } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
用二维码进行添加好友获取好友信息是用到VCard
微信扫码登陆网页原理:通过堵塞等待的长连接,近乎实时的获得信息。 对于验证过程,Open API 一般是通过授权令牌(Token)来解决的,原理是当用户通过授权后,分配一个限定条件下的令牌(如限制本机访问、限制授权有效时间、限制同时登录设备数等),使获得授权的用户仅在有限的前提下能访问相关服务。 像计算机休眠后曾做的授权就自动收回了,这样就有效的避免了在别人电脑上(尤其是网吧)打开,但忘记关闭或退出这类安全问题了。
实现可借鉴已有博客:https://www.cnblogs.com/zijun/p/3580125.html