简单的用java编写生成一个二维码

  1. 用Java编写二维码,首先会用到qrcode.jar这个jar包需要的话的话,可以下载,这是地址:http://pan.baidu.com/s/1slFDVjR
  2. //方法,属性,代码块  
  3.     //定义一个生成二维码的方法  
  4.     public static void QrcodeImg(String context,String imgPath){  
  5.         //实例化一个Qrcode  
  6.         Qrcode qrcode = new Qrcode();  
  7.           
  8.         //拍错率15%  
  9.         qrcode.setQrcodeErrorCorrect('M');  
  10.           
  11.         //版本  
  12.         qrcode.setQrcodeVersion(7);  
  13.           
  14.         //编码  
  15.         qrcode.setQrcodeEncodeMode('B');  
  16.           
  17.         //  
  18.         int width = 140;  
  19.         int height = 140;  
  20.         BufferedImage bufferImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  21.           
  22.         //绘制工具  
  23.         Graphics2D gs = bufferImage.createGraphics();  
  24.       
  25.         //设置二维码的背景色  
  26.         gs.setBackground(Color.white);  
  27.           
  28.         //前景色  
  29.         gs.setColor(Color.black);  
  30.           
  31.         //定义二维码的绘制区域  
  32.         gs.clearRect(0, 0, width, height);  
  33.           
  34.         try {  
  35.             byte[] contentBytes = context.getBytes("utf-8");  
  36.             boolean[][] codeOut = qrcode.calQrcode(contentBytes);  
  37.             for(int i=0;i<codeOut.length;i++){  
  38.                 for(int j=0;j<codeOut.length;j++){  
  39.                     if(codeOut[j][i]){  
  40.                         //如果在这个位置是真的,就涂成黑色  
  41.                         gs.fillRect(j*3+2, i*3+2, 3, 3);  
  42.                     }  
  43.                 }  
  44.             }  
  45.             gs.dispose();  
  46.               
  47.             File imgFile = new File(imgPath);  
  48.             try {  
  49.                 ImageIO.write(bufferImage, "png", imgFile);  
  50.                 System.out.println("二维码生成成功!!!");  
  51.             } catch (IOException e) {  
  52.                 e.printStackTrace();  
  53.             }  
  54.         } catch (UnsupportedEncodingException e) {  
  55.             e.printStackTrace();  
  56.         }  
  57.     }  
  58.       
  59.     public static void main(String[] args) {  
  60.         QrcodeImg("二维码中的内容", "c:/myclass/lan.png");  
  61.     } 
posted @ 2017-09-26 17:04  番茄爱上西红柿  阅读(658)  评论(0)    收藏  举报