1、引入jar包
dependency官網地址:https://zxing.github.io/zxing/dependency-info.html
<!-- 核心包-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
2、編寫代碼
package com.liban.demo.util;
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 java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.EnumMap;
//使用的zxing案例
public class ZXingQrcodeUtil {
private static final int BLACK = 0xFF000000;// 用於設置圖案的顏色
private static final int WHITE = 0xFFFFFFFF; // 用於背景色
// 設置二維碼中間圖片的寬高
private static final int imageWidth = 60;
private static final int imageHeight = 60;
private static final EnumMap<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(
EncodeHintType.class);
static {
/*
* 二維碼的糾錯級別(排錯率),4個級別: L (7%)、 M (15%)、 Q (25%)、 H (30%)(最高H)
* 糾錯信息同樣存儲在二維碼中,糾錯級別越高,糾錯信息佔用的空間越多,那麼能存儲的有用訊息就越少;共有四級; 選擇M,掃描速度快。
*/
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
// 二維碼邊界空白大小 1,2,3,4 (4爲默認,最大)
hints.put(EncodeHintType.MARGIN, 1);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
}
//獲得生成二維碼後的圖像
public BufferedImage Encode_QR_CODE(String contents, int width,
int height) throws WriterException, IOException {
//編碼,返回BitMatrix對象
//1、根據BarcodeFormat編碼格式,創建對應的QRCodeWriter,然後調用對應的encode方法
//2、根據算法結果放入BitMatrix的bits[]中,matrix.get(x, y)方法中根據算法返回true or false
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,// 要編碼的內容
BarcodeFormat.QR_CODE,//編碼方式,QR_CODE是二維碼,還有條形碼 等等...
width, // 條形碼的寬度
height, // 條形碼的高度
hints);// 生成條形碼時的一些配置,此項可選
//編碼後的BitMatrix轉換成BufferedImage
BufferedImage image = toBufferedImage(bitMatrix);
// 設置logo圖標
image = LogoMatrix(image);
return image;
}
//編碼後的BitMatrix轉換成BufferedImage
public BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
//構造一個 BufferedImage義的圖像類型的一個BufferedImage
//第三參數爲 type of the created image
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
//將此 BufferedImage中的像素設置爲指定的RGB值。
//matrix.get(x, y) true means black
image.setRGB(x, y, (matrix.get(x, y) ? BLACK : WHITE));
}
}
return image;
}
/**
* 設置 logo圖片
* @param matrixImage 源二維碼圖片
* @return 返回帶有logo的二維碼圖片
* @throws IOException
*/
public BufferedImage LogoMatrix(BufferedImage matrixImage)
throws IOException {
/**
* 讀取二維碼圖片,並構建繪圖對象
*/
//創建一個 Graphics2D ,可以用來繪製這個 BufferedImage 。
Graphics2D g2 = matrixImage.createGraphics();
//logo開始的繪畫X座標
int centerX = matrixImage.getMinX() + matrixImage.getWidth() / 2
- imageWidth / 2;
//logo開始的繪畫Y座標
int centerY = matrixImage.getMinY() + matrixImage.getHeight() / 2
- imageHeight / 2;
/**
* 讀取Logo圖片
*/
URL url =Thread.currentThread().getContextClassLoader().getResource("images/logo.png");
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
File file = new File(filePath);
//將圖片加載到內存
BufferedImage logo = ImageIO.read(new FileInputStream(file));
// 開始繪製圖片
g2.drawImage(logo, centerX, centerY, imageWidth, imageHeight, null);// 繪製
//處理此圖形上下文並釋放其正在使用的任何系統資源
g2.dispose();
//刷新此Image對象正在使用的所有可重建資源, 圖像被重置爲類似於首次創建的狀態
matrixImage.flush();
return matrixImage;
}
//轉成byte[]
public byte[] imageToBytes(BufferedImage bImage, String format) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(bImage, format, out);
} catch (IOException e) {
e.printStackTrace();
}
//toByteArray方法 > Arrays.copyOf(buf, count)
// > System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
//複製進一個新的數組,並返回copy的數組
return out.toByteArray();
}
public static void main(String[] args) throws WriterException, IOException{
ZXingQrcodeUtil zXingQrcodeUtil = new ZXingQrcodeUtil();
BufferedImage image=zXingQrcodeUtil.Encode_QR_CODE("二維碼內容", 200, 200);
//寫出圖像到 File ,write方法也可以寫入到指定的OutputStream
ImageIO.write(image, "png", new File("e:\\qrcode1.png"));
//轉成byte數組 可用於網絡數據傳輸,也可將其存入數據庫
byte[] bytes = zXingQrcodeUtil.imageToBytes(image, "png");
}
}