1. 程式人生 > >java生成一維碼和二維碼

java生成一維碼和二維碼

這兩天想了解一下二維碼是怎樣生成的。然後在網上看了很多資料,也有很多原始碼可以直接用的。我也沒有自己寫,也是拿著原始碼進行看和修改的,然後生成自己想要的二維碼和一維碼,還是很不錯的,所以分享一下。
首先第一步,需要匯入jar包,我把我用的jar包放上來吧

將包匯入好專案之後就可以開始寫程式碼了,先來談談一個簡單的生成二維碼和一維碼。想直接使用的可以複製程式碼之直接可以用。
下面是MatrixUtil 類,全部生成一維碼和二維碼的方法都在裡面,不過都是生成最簡單的樣式,樣式可以自己修改。

package com.zlf.qrcode2;

import com.google.zxing.BarcodeFormat; 
import
com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.EncodeHintType; import com.google.zxing.LuminanceSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.Result; import com.google.zxing.WriterException; //import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import javax.imageio.ImageIO; import java.io.File; import java.io.OutputStream; import java.io.IOException; import java.util.Hashtable; import java.awt.image.BufferedImage; /** * 使用ZXing2.3,生成條碼的輔助類。可以編碼、解碼。編碼使用code包,解碼需要javase包。 */
public final class MatrixUtil { private static final String CHARSET = "utf-8"; private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; /** * 禁止生成例項,生成例項也沒有意義。 */ private MatrixUtil() { } /** * 生成矩陣,是一個簡單的函式,引數固定,更多的是使用示範。 * @param text * @return */ public static BitMatrix toQRCodeMatrix(String text, Integer width, Integer height) { if (width == null || width < 300) { width = 300; } if (height == null || height < 300) { height = 300; } // 二維碼的圖片格式 Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); // 內容所使用編碼 hints.put(EncodeHintType.CHARACTER_SET, CHARSET); BitMatrix bitMatrix = null; try { bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); } catch (WriterException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 生成二維碼 // File outputFile = new File("d:"+File.separator+"new.gif"); // MatrixUtil.writeToFile(bitMatrix, format, outputFile); return bitMatrix; } /** * 將指定的字串生成二維碼圖片。簡單的使用示例。 * @param text * @param file * @param format * @return */ public boolean toQrcodeFile(String text, File file, String format) { BitMatrix matrix = toQRCodeMatrix(text, null, null); if (matrix != null) { try { writeToFile(matrix, format, file); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; } /** * 根據點矩陣生成黑白圖。 */ public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); } } return image; } /** * 將字串編成一維條碼的矩陣 * @param str * @param width * @param height * @return */ public static BitMatrix toBarCodeMatrix(String str, Integer width, Integer height) { if (width == null || width < 200) { width = 200; } if (height == null || height < 50) { height = 50; } try { // 文字編碼 Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); BitMatrix bitMatrix = new MultiFormatWriter().encode(str, BarcodeFormat.CODE_128, width, height, hints); return bitMatrix; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 根據矩陣、圖片格式,生成檔案。 */ public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); } } /** * 將矩陣寫入到輸出流中。 */ public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } /** * 解碼,需要javase包。 * @param file * @return */ /*public static String decode(File file) { BufferedImage image; try { if (file == null || file.exists() == false) { throw new Exception(" File not found:" + file.getPath()); } image = ImageIO.read(file); LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; // 解碼設定編碼方式為:utf-8, Hashtable hints = new Hashtable(); hints.put(DecodeHintType.CHARACTER_SET, CHARSET); result = new MultiFormatReader().decode(bitmap, hints); return result.getText(); } catch (Exception e) { e.printStackTrace(); } return null; } */ }

接下來是Test測試類,程式碼更簡單。

package com.zlf.qrcode2;

import java.io.File; 

public class Test {   

    /**
     * 測試函式。簡單地將指定的字串生成二維碼圖片。
     */ 
    public static void main(String[] args) throws Exception {   
        String text = "1234567890";   
        String result; 
        String format = "jpg";   
        //生成二維碼   
        File outputFile = new File("j:"+File.separator+"rqcode.jpg");   
        MatrixUtil.writeToFile(MatrixUtil.toQRCodeMatrix(text, null, null), format, outputFile);   
        System.out.println("success1");
        //result = MatrixUtil.decode(outputFile); 
        //System.out.println(result); 
          //生成條形碼 
        outputFile = new File("j:"+File.separator+"barcode.jpg");   
        MatrixUtil.writeToFile(MatrixUtil.toBarCodeMatrix(text, null, null), format, outputFile); 
        System.out.println("success2");
        //result = MatrixUtil.decode(outputFile); 
        //System.out.println(result); 
    }   

}   

一維碼和二維碼效果圖
這裡寫圖片描述

這裡寫圖片描述

接下來主要講一下二維碼的生成吧,因為現在二維碼比較火,動不動就手機掃一掃。為了製作一個稍微有特點的二維碼。我另起了一個專案,不過jar包還是通用的。然後有這幾個類。MatrixToImageWriter類QRCodeFactory類和測試類Qrest

MatrixToImageWriter類主要的功能也是生成二維碼圖片

package com.zlf.qrcode;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.google.zxing.common.BitMatrix;

/*
  二維碼的生成需要藉助MatrixToImageWriter類,該類是由Google提供的,可以將該類直接拷貝到原始碼中使用,當然你也可以自己寫個
  生產條形碼的基類
 */
public class MatrixToImageWriter {
    private static final int BLACK = 0xFF000000;//用於設定圖案的顏色
    private static final int WHITE = 0xFFFFFFFF; //用於背景色

    private MatrixToImageWriter() {
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y,  (matrix.get(x, y) ? BLACK : WHITE));
//                image.setRGB(x, y,  (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file,String logUri) throws IOException {

        System.out.println("write to file");
        BufferedImage image = toBufferedImage(matrix);
        //設定logo圖示
        QRCodeFactory logoConfig = new QRCodeFactory();
        image = logoConfig.setMatrixLogo(image, logUri);

        if (!ImageIO.write(image, format, file)) {
            System.out.println("生成圖片失敗");
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }else{
            System.out.println("圖片生成成功!");
        }
    }

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream,String logUri) throws IOException {

        BufferedImage image = toBufferedImage(matrix);

        //設定logo圖示
        QRCodeFactory logoConfig = new QRCodeFactory();
        image = logoConfig.setMatrixLogo(image, logUri);

        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
}

QRCodeFactory類的功能主要是編寫自己特定製作,比如給二維碼新增一個logo,給二維碼新增文字說明。

package com.zlf.qrcode;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
 * 本類用於對我們二維碼進行引數的設定,生成我們的二維碼:
 * @author kingwen
 */
public class QRCodeFactory {

    /**
     * 給生成的二維碼新增中間的logo
     * @param matrixImage 生成的二維碼
     * @param logUri      logo地址
     * @return            帶有logo的二維碼
     * @throws IOException logo地址找不到會有io異常
     */
     public BufferedImage setMatrixLogo(BufferedImage matrixImage,String logUri) throws IOException{
         /**
          * 讀取二維碼圖片,並構建繪圖物件
          */
         Graphics2D g2 = matrixImage.createGraphics(); 
         int matrixWidth = matrixImage.getWidth();
         int matrixHeigh = matrixImage.getHeight();

         /**
          * 讀取Logo圖片
          */
         BufferedImage logo = ImageIO.read(new File(logUri));

         //開始繪製圖片
         g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);
         //繪製邊框 
         BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); 
         // 設定筆畫物件
         g2.setStroke(stroke);
         //指定弧度的圓角矩形
         RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
         g2.setColor(Color.white);
         // 繪製圓弧矩形
         g2.draw(round);

         //設定logo 有一道灰色邊框
         BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); 
         // 設定筆畫物件
         g2.setStroke(stroke2);
         RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
         g2.setColor(new Color(128,128,128));
         g2.draw(round2);// 繪製圓弧矩形


         Font font = new Font("Freestyle Script", Font.BOLD, 80);
         g2.setFont(font);
         g2.drawString("my love", matrixWidth/5*1+50, matrixHeigh/5*4-10);


         g2.dispose();
         matrixImage.flush() ;
         return matrixImage ;

     }



     /**
      * 建立我們的二維碼圖片
      * @param content            二維碼內容
      * @param format             生成二維碼的格式
      * @param outFileUri         二維碼的生成地址
      * @param logUri             二維碼中間logo的地址
      * @param size               用於設定圖片大小(可變引數,寬,高)
      * @throws IOException       丟擲io異常
      * @throws WriterException   丟擲書寫異常
      */
     public  void CreatQrImage(String content,String format,String outFileUri,String logUri, int ...size) throws IOException, WriterException{


        int width = 430; // 二維碼圖片寬度 430 
         int height = 430; // 二維碼圖片高度430    

         //如果儲存大小的不為空,那麼對我們圖片的大小進行設定
        if(size.length==2){
        width=size[0];
        height=size[1];
        }else if(size.length==1){
           width=height=size[0];
        }


         Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
          // 指定糾錯等級,糾錯級別(L 7%、M 15%、Q 25%、H 30%)
         hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
         // 內容所使用字符集編碼
         hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    
        //hints.put(EncodeHintType.MAX_SIZE, 350);//設定圖片的最大值
        //hints.put(EncodeHintType.MIN_SIZE, 100);//設定圖片的最小值
         hints.put(EncodeHintType.MARGIN, 1);//設定二維碼邊的空度,非負數

         BitMatrix bitMatrix = new MultiFormatWriter().encode(content,//要編碼的內容
                 //編碼型別,目前zxing支援:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
                 //Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
                 //MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
                 BarcodeFormat.QR_CODE,
                 width, //條形碼的寬度
                 height, //條形碼的高度
                 hints);//生成條形碼時的一些配置,此項可選

         // 生成二維碼圖片檔案
         File outputFile = new File(outFileUri);

         //指定輸出路徑    
         System.out.println("輸出檔案路徑為"+outputFile.getPath());

         MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile,logUri);
     }   
}

接下來就是測試Qrest類了,

package com.zlf.qrcode;


import java.io.IOException;

import com.google.zxing.WriterException;

public class Qrest {

    public static void main(String[] args) {

        String content="我莫名奇妙的笑了,只因為想到了你。";
       String logUri="J:/logs/1.jpg"; //J:\\logs\\author.jpg
       String outFileUri="J:/logs/qtCode1.jpg";
       int[]  size=new int[]{430,430};
       String format = "jpg";  

       try {
        new QRCodeFactory().CreatQrImage(content, format, outFileUri, logUri,size);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (WriterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
  }

}

這些程式碼也可以直接複製直接使用的。,現在給看一下我做出來的效果圖。
將自己的個人blog製作成二維碼

參考的文章比較多,現在也記不得網址了,就不粘出來了,如果有侵權的聯絡我刪除。