使用zxing生成和下载二维码-服务器端

使用zxing生成和下载二维码


时间:2019年4月30日14:31:22


Maven依赖:

<dependency>
	<groupId>com.google.zxinggroupId>
    <artifactId>javaseartifactId>
    <version>3.2.1version>
dependency>

HTML代码


<img src="/qrcode/getQrCode?content=二维码内容" />
<a href="/qrcode/getQrCode?content=二维码内容&isDown=1&name=文件名(不用带后缀)">下载二维码a>

服务器端代码
1.工具类代码

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

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
/**
 * 生成包含字符串信息的二维码图片
 * @param content 二维码携带信息
 * @param qrCodeSize 二维码图片大小
 * @param imageFormat 二维码的格式
 * @throws IOException 
 */
public static BufferedImage createQrCode(String content, int qrCodeSize, String imageFormat) throws WriterException, IOException{
    Hashtable<EncodeHintType, Object> hintMap = new Hashtable<EncodeHintType, Object>();
    // 编码设置为 UTF-8
    hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    // 设置二维码四周白色区域大小
    hintMap.put(EncodeHintType.MARGIN,2);
    // 设置二维码的容错性
    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-65, matrixWidth-65, 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-33, j-33, 2, 2);
            }
        }
    }
    return image;
}
/**
* 读二维码并输出携带的信息
 */
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());  
}

2.Controller代码

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@RequestMapping("getQrCode")
public void getQrCode(String content, String isDown, String name, String author, HttpServletRequest request, HttpServletResponse response){
	request.setCharacterEncoding("UTF-8");
    if(content==null||content.length()<1){
        log.error("二维码内容错误");
        return;
    }
    try {
        log.info("开始生成二维码:"+name+" 内容:"+content);
        if(!author.equals("张闫")){
            //可能存在的get请求中文乱码问题
            log.info("遇见中文乱码...");
            content = new String(content.getBytes("ISO8859-1"),"UTF-8");
        }
        if(isDown==null||"".equals(isDown)){
            log.info("获取二维码...");
            response.setDateHeader("expries", -1);
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
        }else{
            log.info("下载二维码");
            response.setContentType("image/jpeg");
            name = URLEncoder.encode(name, "utf-8");
            response.setHeader("content-disposition","attachment;filename="+name+".jpg");
        }
        ImageIO.write(QrCodeCreateUtil.createQrCode(content,500,"jpg"), "jpg", response.getOutputStream());
    } catch (Exception e) {
        log.error("获取二维码失败!",e);
    }
}

你可能感兴趣的:(使用zxing生成和下载二维码-服务器端)