java生成二維碼工具類


package com.runtime.extend.utils.CodeCreate;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
//import com.google.zxing.client.j2se.BufferedImageLuminanceSource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;

/**
*     
* 項目名稱:bic-xxzthzsgl   
* 類名稱:qrCodeCreateUtil   
* 類描述:二維碼生成工具類
* 創建人:MFJ   
* 創建時間:2019/1/10 8:50   
* 修改備注:   
*
* @version  1.0       
*/
public class qrCodeCreateUtil {

/**
* 生成包含字符串信息的二維碼圖片
*
* @param outputStream 文件輸出流路徑
* @param content 二維碼攜帶信息
* @param qrCodeSize 二維碼圖片大小
* @param imageFormat 二維碼的格式
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
//設置二維碼糾錯級別MAP
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矯錯級別
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//創建比特矩陣(位矩陣)QR碼編碼的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
// 使BufferedImage勾畫QRCode (matrixWidth 是行二維碼像素點)
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth - 200, matrixWidth - 200, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// 使用比特矩陣畫並保存圖像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i - 100, j - 100, 1, 1);
}
}
}
return ImageIO.write(image, imageFormat, outputStream);
}

/**
* 讀二維碼並輸出攜帶的信息
*/
// public static void readQrCode(InputStream inputStream) throws IOException{
// //從輸入流中獲取字符串信息
// BufferedImage image = ImageIO.read(inputStream);
// //將圖像轉換為二進制位圖源
// LuminanceSource source = new BufferedImageLuminanceSource(image);
// BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
// QRCodeReader reader = new QRCodeReader();
// Result result = null ;
// try {
// result = reader.decode(bitmap);
// } catch (ReaderException e) {
// e.printStackTrace();
// }
// System.out.println(result.getText());
// }


public static void main(String[] args) throws IOException, WriterException {

createQrCode(new FileOutputStream(new File("d:\\qrcode.jpg")),"WE1231238239128sASDASDSADSDWEWWREWRERWSDFDFSDSDF123123123123213123",900,"JPEG");
// readQrCode(new FileInputStream(new File("d:\\qrcode.jpg")));
}


}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM