java產生二維碼工具類__java

來源:互聯網
上載者:User

如下為java產生二維碼工具類,可以選擇組建檔案,或者直接在頁面產生



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;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.alibaba.fastjson.JSONObject;import com.google.zxing.BarcodeFormat;import com.google.zxing.Binarizer;import com.google.zxing.BinaryBitmap;import com.google.zxing.DecodeHintType;import com.google.zxing.EncodeHintType;import com.google.zxing.LuminanceSource;import com.google.zxing.MultiFormatReader;import com.google.zxing.MultiFormatWriter;import com.google.zxing.NotFoundException;import com.google.zxing.Result;import com.google.zxing.WriterException;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;/** *  * 二維碼工具類 * @see [相關類/方法] * @since [產品/模組版本] */public class QRCodeUtil{        private static final Logger log = LoggerFactory.getLogger(QRCodeUtil.class);            /**     *      * 產生二維碼檔案測試     * @param filePath 檔案路徑     * @param fileName 檔案名稱     * @param number 編號     * @param phone 手機號     * @see [類、類#方法、類#成員]     */    public static void generatEncodeTest(String filePath, String fileName, String number, String phone)    {                int width = 200; // 映像寬度        int height = 200; // 映像高度        String format = "png";// 映像類型                JSONObject json = new JSONObject();          json.put("number",number);          json.put("phone", phone);          String content = json.toJSONString();// 內容                 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 number 編號     * @param phone 手機號     * @see [類、類#方法、類#成員]     */    public static void generatEncode(HttpServletResponse response, String number, String phone)    {    JSONObject json = new JSONObject();          json.put("number",number);          json.put("phone", phone);          String content = json.toJSONString();// 內容                 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("二維碼輸出成功");        }        catch (WriterException e)        {            e.printStackTrace();            log.error("二維碼輸出異常");        }        catch (IOException e)        {            e.printStackTrace();            log.error("二維碼輸出異常");        }    }        public static void main(String[] args)    {        generatEncodeTest("D:\\","zxing.png","001","13019931996");        parseDecodeTest("D:\\zxing.png");    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.