Java使用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。</span></span> <S.LENGTH;I++){ pre="" <="" last);="" +="" consume:?="" system.out.println(?time="" start;="" -="" last="end" end="System.currentTimeMillis();" qrcodetest.create_image(string);="" ;="" string="" start="System.currentTimeMillis();" long="" exception="" throws="" args)="" main(string[]="" void="" static="" public="" e.printstacktrace();="" e)="" (exception="" catch="" f);="" ?jpg?,="" imageio.write(bi,="" f.createnewfile();="" if(!f.exists())="" file(?e:\qrcodetest\a.jpg?);="" f="new" file="" bi.flush();="" g.dispose();="" }="" g.fillrect(j2,i2,2,2);="" {="" (s[j][i])="" if="" j="0;j<s.length;j++){" (int="" for=""></S.LENGTH;I++){>代碼如下: 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://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);
}
} </pre></span></span></span>生成的二維碼如下:<br />