package common;
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.QRCodeWriter;
import sdk.LogUtil;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class zxingQrCodeUtil {
/**
* 生成web版本二维码(Stream)
*
* @param contents 要生成二维码的内容
* @param format 二维码图片格式
* @param response response对象
* @param width 二维码宽度
* @param height 二维码高度
* @throws IOException
*/
public static void getQrCodeToStream(String contents, String format, HttpServletResponse response, int width, int height) throws IOException {
if (contents != null && !"".equals(contents)) {
ServletOutputStream stream = null;
try {
stream = response.getOutputStream();
// QRCodeWriter writer = new QRCodeWriter();
// BitMatrix bitMatrix = writer.encode(contents, BarcodeFormat.QR_CODE, width, height);
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, DemoBase.encoding);
BitMatrix bitMatrix = multiFormatWriter.encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
} catch (WriterException e) {
e.printStackTrace();
LogUtil.writeErrorLog("生成二维码失败!");
} finally {
if (stream != null) {
stream.flush();
stream.close();
}
}
}
}
/**
* 生成web版本二维码(img)
* @param contents 要生成二维码的内容
* @param format 二维码图片格式
* @param file 二维码图片地址
* @param width 二维码宽度
* @param height 二维码高度
* @throws IOException
*/
public static void getQrCodeToFile(String contents, String format, File file, int width, int height) throws IOException {
if (contents != null && !"".equals(contents)) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, String> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, DemoBase.encoding);
BitMatrix bitMatrix = multiFormatWriter.encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToFile(bitMatrix, format, file);
} catch (WriterException e) {
e.printStackTrace();
LogUtil.writeErrorLog("生成二维码失败!");
}
}
}
}