`
zzc1684
  • 浏览: 1190636 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

使用QRCode生成二维码

阅读更多

QRcode是日本人94年开发出来的。首先去QRCode的官网http://swetake.com/qrcode/java/qr_java.html,把要用的jar包下下来,导入到项目里去。 qrcode需要设置一个版本号,这个版本号代表你生成的二维码的像素的大小。版本1是21*21的,版本号每增加1,边长增加4。也就是说版本7的大小 是45 * 45的。版本号最大值是40。另外,版本7的编码的字节数如果超过了119,那么将无法编码,我按照官方文档提供的像素点个数与编码的字节数公式换算,完 全没法算出这个出来119。官方文档在这里:http://swetake.com/qrcode/qr1_en.html。欢迎了解的情况的高手跟帖回复。

代码如下:

import java.io.*;  
    import java.util.Date;  
       
    import java.awt.*;  
    import java.awt.image.*;  
    import javax.imageio.*;  
  
   import com.swetake.util.Qrcode;  
       
public class QRCodeTest {  
    static int width = 90;  
    static int height = 90;  
       
     public QRCodeTest()  
     {  
     }  
       
     public static void create_image(String sms_info)throws Exception{  
      try{  
            Qrcode testQrcode =new Qrcode();  
                testQrcode.setQrcodeErrorCorrect('M');  
                testQrcode.setQrcodeEncodeMode('B');  
                testQrcode.setQrcodeVersion(7);  
                String testString = sms_info;  
                byte[] d = testString.getBytes("gbk");  
                BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);  
                Graphics2D g = bi.createGraphics();  
                g.setBackground(Color.WHITE);  
                g.clearRect(0, 0, width, height);  
                g.setColor(Color.BLACK);  
                  
                // 限制最大字节数为119  
                if (d.length>0 && d.length <120){  
                    boolean[][] s = testQrcode.calQrcode(d);  
                    for (int i=0;i<s.length;i++){  
                        for (int j=0;j<s.length;j++){  
                            if (s[j][i]) {  
                                g.fillRect(j*2,i*2,2,2);  
                            }  
                        }  
                    }  
                }  
                g.dispose();  
                bi.flush();  
                File f = new File("E:\\QRCodeTest\\a.jpg");  
                if(!f.exists()) f.createNewFile();  
                ImageIO.write(bi, "jpg", f);  
            }  
            catch (Exception e) {  
                e.printStackTrace();  
            }   
     }  
       
     public static void main(String[] args) throws Exception {  
         long start = System.currentTimeMillis();  
         String string = "http://localhost/xx.apk";  
            QRCodeTest.create_image(string);  
            long end = System.currentTimeMillis();  
            long last = end  - start;  
            System.out.println("time consume:" + last);  
        }   
    }  

 生成的二维码如下:

20130717180846171.jpg

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics