java生成二維碼


package com.dosion.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.util.HashMap;
import java.util.Map;
public class QRCodeUtil {
    private static final Logger log = LoggerFactory.getLogger(QRCodeUtil.class);

    /**
     *
     * 生成二維碼文件測試
     * @param filePath 文件路徑
     * @param fileName 文件名
     * @param
     * @param
     * @see [類、類#方法、類#成員]
     */
    public static void generatEncodeTest(String filePath, String fileName,String url)
    {

        int width = 200; // 圖像寬度
        int height = 200; // 圖像高度
        String format = "png";// 圖像類型

        String content = url;// 內容

        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try
        {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩陣
            String path = FileSystems.getDefault().getPath(filePath, fileName).toString();
            File file = new File(path);
            MatrixToImageWriter.writeToFile(bitMatrix, format, file);// 輸出圖像
            System.out.println("二維碼輸出成功");
            System.out.println("圖片地址:" + filePath + fileName);
            System.out.println("---------------------------");
        }
        catch (WriterException e)
        {
            e.printStackTrace();
            System.out.println("二維碼輸出異常");
        }
        catch (IOException e)
        {
            e.printStackTrace();
            System.out.println("二維碼輸出異常");
        }
    }

    /**
     *
     * 解析二維碼內容測試
     * @param filePath 二維碼絕對路徑
     * @see [類、類#方法、類#成員]
     */
    public static void parseDecodeTest(String filePath)
    {
        BufferedImage image;
        try
        {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 對圖像進行解碼
            JSONObject content = JSONObject.parseObject(result.getText());

            StringBuffer sb = new StringBuffer();
            sb.append("編號:")
                    .append(content.getString("number"))
                    .append("\r\n")
                    .append("手機號碼:")
                    .append(content.getString("phone"));
            String returnText = sb.toString();
            System.out.println(returnText);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (NotFoundException e)
        {
            e.printStackTrace();
        }
    }


    /**
     *
     * 生成二維碼輸出流
     *  在jsp頁面中直接展示時使用
     *  無須保存 即生成即展示
     * @param response
     * @param
     * @see [類、類#方法、類#成員]
     */
    public static void generatEncode(HttpServletResponse response, String url)
    {

        String content = url;// 內容
        int width = 200; // 圖像寬度
        int height = 200; // 圖像高度
        String format = "png";// 圖像類型
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        try
        {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);// 生成矩陣
            MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream());// 輸出圖像
            log.info("二維碼輸出成功");
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
        catch (WriterException e)
        {
            e.printStackTrace();
            log.error("二維碼輸出異常");
        }
        catch (IOException e)
        {
            e.printStackTrace();
            log.error("二維碼輸出異常");
        }
    }

}

引入文件

<dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.0</version>
        </dependency>

測試

public void imge(String id,HttpServletResponse response){
QRCodeUtil.generatEncode(response,"http://"+srt);
}


免責聲明!

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



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