天天看點

二維碼生成技術

常用的二維碼生成的方法中有日本人寫的QR和谷歌提供的zxing,生成的常見的方形的二維碼 。

項目中用到的jar包,在博文下面的分享的項目源碼中的lib目錄下。可自行下載下傳。

1.google提供的zxing

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.EncodeHintType;
import javax.imageio.ImageIO;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.BarcodeFormat;
public class QRCodeUtil {
    private static final int BLACK = ;
    private static final int WHITE = ;
    public void GenerateQRCode(String path,String content) {

        int width = ;
        int height = ;
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    //  hints.put(EncodeHintType.MARGIN, 2);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);
            //高版本的jdk可以直接用這個方法,我的jdk1.6沒有Path這個類
            //MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(path).toPath());


            BufferedImage image=toBufferedImage(bitMatrix);
            ImageIO.write(image, "bmp", new File(path));

        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage bufferedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_BYTE_GRAY);
        for (int x = ; x < width; x++) {
            for (int y = ; y < height; y++) {
                bufferedImage.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return bufferedImage;
    }
    public void DecodeQRCode(String filePath){
         BufferedImage image;  
         try {  
             image = ImageIO.read(new File(filePath));  
             LuminanceSource source = new BufferedImageLuminanceSource(image);  
             Binarizer binarizer = new HybridBinarizer(source);  
             BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);  
             Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();  
             hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");  
             Result result=new MultiFormatReader().decode(binaryBitmap, hints);

             System.out.println("圖檔中内容:  "+result);  
             System.out.println("圖檔中格式:"+ result.getBarcodeFormat());  
         } catch (IOException e) {  
             e.printStackTrace();  
         } catch (NotFoundException e) {  
             e.printStackTrace();  
         }  
     }  

    public static void main(String[] args) {
        String content = "http://www.baidu.com";
        String path = "d:/java/img.bmp";  
        new QRCodeUtil().GenerateQRCode(path,content);
        new QRCodeUtil().DecodeQRCode(path);
    }

}
           

生成的二維碼如下:(掃碼會跳到我們設定的百度首頁)

二維碼生成技術

2.QR方法

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.imageio.ImageIO;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
import com.swetake.util.Qrcode;
public class QRCodeUtil {
    public static void main(String[] args) throws Exception {
        String content = "http://www.baidu.com";
        String path = "d:/java/img2.bmp";
        new QRCodeUtil().GeneratorQRCode(content, path);
        new QRCodeUtil().DecodeQRImg(path);
    }
    public  void GeneratorQRCode(String content,String path) throws IOException{
        Qrcode x=new Qrcode();  
        x.setQrcodeErrorCorrect('M');//糾錯等級 
        x.setQrcodeEncodeMode('B');//N代表數字,A代表a-Z,B代表其他字元  
        x.setQrcodeVersion();//版本  

        int width =  +  * ( - );//設定二維碼的大小公式:67 + 12 * (version - 1)  
        int height =  +  * ( - );  

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
        Graphics2D gs = bufferedImage.createGraphics();  

        gs.setBackground(Color.WHITE);  
        gs.setColor(Color.BLACK);  
        gs.clearRect(, , width, height);//清除畫闆的内容  
        int pixoff = ;//添加一個偏移量  

        byte[] d = content.getBytes("utf-8");  
        if (d.length> && d.length <){  
            boolean[][] s = x.calQrcode(d);  

            for (int i=;i<s.length;i++){  
            for (int j=;j<s.length;j++){  
                if (s[j][i]) {  
                gs.fillRect(j* + pixoff,i* + pixoff,,);  
                }  
            }  
            }  
        }  
        gs.dispose();  
        bufferedImage.flush();  
        ImageIO.write(bufferedImage, "png", new File(path));  
    }
    public void DecodeQRImg(String path){

        String result;
        try {
            //讀取驗證碼圖檔
            BufferedImage bufferedImage = ImageIO.read(new File(path));
            // 調用方法
            QRCodeDecoder codeDecoder = new QRCodeDecoder();
            result = new String(codeDecoder.decode(new MyQRCodeImage(
                    bufferedImage)), "utf-8");
            System.out.println("二維碼的内容為:" + result);
        } catch (DecodingFailedException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
           
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 x, int y) {
        return bufferedImage.getRGB(x, y);

    }

    public int getWidth() {

        return bufferedImage.getWidth();
    }

}
           

生成的二維碼如下:

二維碼生成技術

[項目的源碼位址:]

(http://pan.baidu.com/s/1i5cG7Gh)