使用zxing生成二維碼並前臺顯示
##業務需求:
近期項目中要使用將信息存入二維碼,供用戶微信掃描讀取!提高實際工作中得工作效率
##思路:
-**1.在前臺將需要生成得信息,通過servlet傳入後端
-**2.將信息進行處理,使用zxing生成二維碼圖片!
-**3.因爲要返回到前臺所以就不生成具體圖片文件。所以直接將生成的二維碼二進制圖片流
-**4.將得到的圖片流,通過輸出流傳到前臺
##工具簡介:
ZXing是一個開放源碼的,用Java實現的多種格式的1D/2D條碼圖像處理庫,它包含了聯繫到其他語言的端口。Zxing可以實現使用手機的內置的攝像頭完成條形碼的掃描及解碼。該項目可實現的條形碼編碼和解碼。
##方法實現:
1.通過maven引入zxing的jar包
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.1</version>
</dependency>
2.寫QRUtils工具包
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Arrays;
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.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二維碼尺寸
private static final int QRCODE_SIZE = 300;
// LOGO寬度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入圖片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println(""+imgPath+" 該文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 壓縮LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 繪製縮小後的圖
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
//獲取生成二維碼的圖片流
public static ByteArrayOutputStream encodeIO(String content,String imgPath,Boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
//創建儲存圖片二進制流的輸出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//將二進制數據寫入ByteArrayOutputStream
ImageIO.write(image, "jpg", baos);
return baos;
}
//測試
public static void main(String[] args) throws Exception {
String text = "ifarm";
//QRCodeUtil.encode(text, "D:\\圖片\\武僧2.jpg", "d:/MyWorkDoc", true);
//String decode = QRCodeUtil.decode("D:\\MyWorkDoc\\32533141.jpg");
ByteArrayOutputStream encodeIO = QRCodeUtil.encodeIO(text, "D:\\圖片\\武僧2.jpg", true);
//輸入數組
System.out.println(Arrays.toString(encodeIO.toByteArray()));
}
}
3.後臺Controller
@RequestMapping(value = "/getQRCode", method = RequestMethod.GET)
public void getQRCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
//獲取前臺傳入的信息,此處可操作性很大,大家可以通過自己查詢數據庫,或者通過判斷填入其他信息
String content = request.getParameter("content");
//二維碼圖片中間logo
String imgPath = "";
Boolean needCompress = true;
//通過調用我們的寫的工具類,拿到圖片流
ByteArrayOutputStream out = QRCodeUtil.encodeIO(content, imgPath, needCompress);
//定義返回參數
response.setCharacterEncoding("UTF-8");
response.setContentType("image/jpeg;charset=UTF-8");
response.setContentLength(out.size());
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(out.toByteArray());
outputStream.flush();
outputStream.close();
}
4.前端
-html
<h1>測試二維碼頁面</h1>
<div class="input-group">
<span class="input-group-addon" >耳號</span>
<input type="text" class="form-control" placeholder="請輸入" id="swineEar">
<span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>
</div>
<div>
<div style="float: left;">
<img src="" id="npcImg" width="300" height="300"/>
<input type="hidden" id="photo" name="photo"/>
</div>
</div>
-js
function doCode () {
$('#npcImg').removeAttr('src')
var npcName = document.getElementById("swineEar").value;
if(npcName === ''){
alert('耳號爲空,不能生成二維碼')
}else{
var img = document.getElementById("npcImg");
img.src = '/getQRCode?content='+npcName;
}
}
##總結:
記錄再此爲爲自己總結,也希望能夠幫到其他人!
具體步驟解析,在代碼中都有註釋,應該不需要做過多解釋了。希望能對大家有所幫助!
正常項目中使用直接copy過去直接就能使用了!
覺得不錯的話,點個拇指!