使用QRCode生成二維碼

jopen 10年前發布 | 63K 次閱讀 二維碼 條形碼/二維碼開發包

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。歡迎了解的情況的高手跟帖回復。</span></span>

代碼如下:

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);  
    }   
}  </pre></span></span></span>生成的二維碼如下:<p></p>

20130717180846171.jpg</span></span>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!