您的位置:首页 > 其它

使用QRCode生成二维码

2016-01-06 14:39 429 查看
我们项目的安卓客户端开发出来了,下载页面上要呈现出二维码以方便移动端以方便移动端用户下载。

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。欢迎了解的情况的高手跟帖回复。

代码如下:

[java]
view plaincopy

    import java.io.*;  
    import java.util.Date;  
       
    import java.awt.*;  
    import java.awt.image.*;  
<span style="white-space:pre">    </span>import javax.imageio.*;  
  
<span style="white-space:pre">    </span>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(<
a1fc
/span>"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://jss.360buy.com/outLinkServicePoint/e4f76f55-8661-4d76-8465-d4cd0e0cc4c5.0.3_Beta_signed_20130609_.apk";  
            QRCodeTest.create_image(string);  
            long end = System.currentTimeMillis();  
            long last = end  - start;  
            System.out.println("time consume:" + last);  
        }   
    }  

生成的二维码如下:



用这个图片扫一扫就可以下载到我们的安卓客户端了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: