Java實現的二維碼生成和解析(QRCode方式)
阿新 • • 發佈:2018-12-19
1.背景
在Java實現的二維碼生成和解析(zxing方式)中採用的是谷歌裡的二維碼生成方式,在這裡將另外的一種二維碼生成方式記錄下來,以方便自己和其他需要的人。
2.二維碼
第一步:匯入相應的jar包。在http://download.csdn.net/detail/u012453843/9838113這個地址中相應的jar包可以下載。
第二步:將下載下來的jar包放入專案中,然後,右擊滑鼠進入Build Path,點選Add Build Path.
第三步:編寫程式碼
二維碼的生成
/** * 生成二維碼 * @param text 需要變成二維碼的內容 * @param name 生成二維碼圖片的名字 * @return pathname 返回二維碼所在的地址 * @throws IOException */ public static String generateQRCode(String text,String name) throws IOException { Qrcode qrcode = new Qrcode(); qrcode.setQrcodeErrorCorrect('M');//設定糾錯等級(分為:L、M、H三個等級) qrcode.setQrcodeEncodeMode('B');//N代表數字、A代表a-Z、B代表其他字元 qrcode.setQrcodeVersion(7);//設定版本 int width = 67+12*(7-1);//設定畫素 二維碼畫素的大小和版本號有關 但是版本號越大 二維碼也越是複雜 這個需要注意 int height = 67+12*(7-1);//設定畫素 //將內容變為特定UTF-8格式編碼的位元組碼 byte [] qrData = text.getBytes("UTF-8"); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); //創造畫筆 Graphics2D gs = bufferedImage.createGraphics(); gs.setBackground(Color.WHITE);//設定背景 gs.setColor(Color.BLACK);//設定畫筆顏色 gs.clearRect(0, 0, width, height);//清除畫板內容 //設定偏移量 int pixoff = 2; boolean [][] d = qrcode.calQrcode(qrData); for(int y=0;y<d.length;y++) { for(int x=0;x<d.length;x++) { if(d[x][y]) { gs.fillRect(x*3+pixoff, y*3+pixoff, 3, 3); } } } gs.dispose(); bufferedImage.flush(); String pathname = "E:\\log\\"+name+".png"; File file = new File(pathname); ImageIO.write(bufferedImage, "png", file); System.out.println("二維碼生成完畢"); return pathname; }
二維碼的解析
/** * 解析二維碼 * @param pathname 二維碼所在地址 * @return 結果 * @throws IOException */ public static String readQRCode(String pathname) throws IOException { File file = new File(pathname); //讀取圖片 BufferedImage bufferedImage = ImageIO.read(file); QRCodeDecoder codeDecoder = new QRCodeDecoder(); //解析出二維碼中的位元組 byte [] data = codeDecoder.decode(new MyQRCodeImage(bufferedImage)); //將位元組資料變為字串 String result = new String(data, "UTF-8"); return result; }
package cn.wl.study.QRCode2; import java.awt.image.BufferedImage; import jp.sourceforge.qrcode.data.QRCodeImage; public class MyQRCodeImage implements QRCodeImage{ BufferedImage bufferedImage; public MyQRCodeImage(BufferedImage bufferedImage) { this.bufferedImage = bufferedImage; } public int getHeight() { return bufferedImage.getHeight(); } public int getPixel(int arg0, int arg1) { return bufferedImage.getRGB(arg0, arg1); } public int getWidth() { return bufferedImage.getWidth(); } }
測試
public static void main(String [] args) throws IOException {
//生成二維碼
String pathname = generateQRCode("http://www.baidu.com", "test2");
System.out.println("二維碼所在地址:"+pathname);
//解析二維碼
String result = readQRCode(pathname);
System.out.println("二維碼中所蘊含的內容為:"+result);
}
參考: