java生成二維碼zxing

java生成二維碼

java生成二維碼的方式有很多,但是我選用的是 ZXingZXing是goole開發的,我個人感覺比較喜歡這套吧。

在這裏插入圖片描述

一、引入依賴

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.0</version>
</dependency>

二、生成二維碼

  • 操作類
package com.mcp.qrcode;

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;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
 
public class EncodeTest {

	/***
	 * 二維碼生成類
	 * @param response
	 * @param logoImages logo圖片
	 * @param contents 二維碼裏的數據
	 * @throws IOException
	 * @throws WriterException
	 */
	public static void Encode_QR_CODE(HttpServletResponse response,String logoImages,String contents) throws IOException, WriterException{
		int width = 430; // 二維碼圖片寬度 300
		int height = 430; // 二維碼圖片高度300

		String format = "gif";// 二維碼的圖片格式 gif
		
		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(contents,//要編碼的內容
				//編碼類型,目前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);//生成條形碼時的一些配置,此項可選
		
		//獲取輸出流
		OutputStream fos = response.getOutputStream();
		BufferedImage Bimage = MatrixToImageWriter.toBufferedImage(bitMatrix);
		MatrixToImageWriter.writeToStream(bitMatrix,format,fos,logoImages);
		if (!ImageIO.write(Bimage, "png", fos)) {
			throw new IOException("Could not write an image ");
		}
		fos.close();
	}
}

  • LogoConfig類,主要處理logo圖標已達到和微信自動的二維碼相近的效果
package com.mcp.qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

/**
 * 二維碼 添加 logo圖標 處理的方法,
 * 模仿微信自動生成二維碼效果,有圓角邊框,logo和二維碼間有空白區,logo帶有灰色邊框
 * @author Administrator sangwenhao
 *
 */
public class LogoConfig {
	
	/**
	 * 設置 logo 
	 * @param matrixImage 源二維碼圖片
     * @param logoImage  logo圖片
	 * @return 返回帶有logo的二維碼圖片
	 * @throws IOException
	 * @author Administrator sangwenhao
	 */
     public BufferedImage LogoMatrix(BufferedImage matrixImage,String logoImage) throws IOException{
    	 /**
          * 讀取二維碼圖片,並構建繪圖對象
          */
         Graphics2D g2 = matrixImage.createGraphics();
    	 
    	 int matrixWidth = matrixImage.getWidth();
    	 int matrixHeigh = matrixImage.getHeight();
    	 
         /**
          * logo圖片在本地獲取
          */
//         BufferedImage logo = ImageIO.read(new File(logoImage));
         // logo圖片在遠程獲取
         URL url = new URL(logoImage);
         BufferedImage logo = ImageIO.read(url);
         //開始繪製圖片
         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);// 繪製圓弧矩形
         
         g2.dispose();
         matrixImage.flush() ;
         return matrixImage ;
     }
    
}

  • 維碼的生成需要藉助MatrixToImageWriter
package com.mcp.qrcode;


import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;


/**
 * 二維碼的生成需要藉助MatrixToImageWriter類
 * 生產條形碼的基類
 */
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 writeToStream(BitMatrix matrix, String format, OutputStream stream,String logoImages) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        //設置logo圖標
        LogoConfig logoConfig = new LogoConfig();
        image = logoConfig.LogoMatrix(image,logoImages);

        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
}
  • 測試
@GetMapping("/b")
public void b(HttpServletResponse response) throws IOException, WriterException {
    // logo背景圖
    String logoImages = "https://avatar.csdnimg.cn/1/0/8/1_qq_41853447_1568005473.jpg" ;
    //二維碼中的數據
    String content = "https://blog.csdn.net/qq_41853447;
    EncodeTest.Encode_QR_CODE(response,logoImages,content);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章