ZxingTest二維碼

public class ZxingTest {
    public static void main(String[] args) throws WriterException, IOException {
        String mecard = "MECARD:N:王**;ORG:杭州;EMAIL:wgshuaiit@163.com;ADR:杭州;NOTE:java開(kāi)發(fā);;";

        // 還是亂碼 mecard = new String(mecard.getBytes("ISO8859-1"), "UTF-8");

        //解決亂碼
        Map<EncodeHintType,String> hints = Maps.newHashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        BitMatrix bitMatrix = new MultiFormatWriter().encode(mecard, BarcodeFormat.QR_CODE, 200, 200,hints);

        MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream("D:/qr.png"));

    }
}
 /**
     * 將客戶信息生成二維碼
     */
    @RequestMapping(value = "/qrcode/{id:\\d+}.png",method = RequestMethod.GET)
    public void makeQrCode(@PathVariable Integer id,HttpServletResponse response) throws IOException, WriterException {
        String mecard = customerService.makeMeCard(id);

        Map<EncodeHintType,String> hints = Maps.newHashMap();
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");

        BitMatrix bitMatrix = new MultiFormatWriter().encode(mecard, BarcodeFormat.QR_CODE,200,200,hints);

        OutputStream outputStream = response.getOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix,"png",outputStream);
        outputStream.flush();
        outputStream.close();
    }
 /**
     * 將客戶信息生成MECard格式
     * @param id
     * @return
     */
    public String makeMeCard(Integer id) {
        Customer customer = customerMapper.findById(id);

        StringBuilder mecard = new StringBuilder("MECARD:");
        if(StringUtils.isNotEmpty(customer.getName())) {
            mecard.append("N:"+customer.getName()+";");
        }
        if(StringUtils.isNotEmpty(customer.getTel())) {
            mecard.append("TEL:"+customer.getTel()+";");
        }
        if(StringUtils.isNotEmpty(customer.getEmail())) {
            mecard.append("EMAIL:"+customer.getEmail()+";");
        }
        if(StringUtils.isNotEmpty(customer.getAddress())) {
            mecard.append("ADR:"+customer.getAddress()+";");
        }
        if(StringUtils.isNotEmpty(customer.getCompanyname())) {
            mecard.append("ORG:"+customer.getCompanyname()+";");
        }
        mecard.append(";");

        return mecard.toString();
    }

使用

div class="box-body" style="text-align: center">

            ![](/makeQrCode.png)
        </div>

工具類

package com.kaishengit.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 二維碼工具類
 */
public class QrCodeUtil {

    // 默認(rèn)二維碼寬度
    private static final int width = 300;
    // 默認(rèn)二維碼高度
    private static final int height = 300;
    // 默認(rèn)二維碼文件格式
    private static final String format = "png";
    // 二維碼參數(shù)
    private static final Map<EncodeHintType, Object> hints = new HashMap();

    static {
        // 字符編碼
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 容錯(cuò)等級(jí) L重贺、M、Q、H 其中 L 為最低, H 為最高
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 二維碼與圖片邊距
        hints.put(EncodeHintType.MARGIN, 2);
    }
    /**
     * 將二維碼圖片輸出到一個(gè)流中
     * @param content 二維碼內(nèi)容
     * @param stream  輸出流
     * @param width   寬
     * @param height  高
     */
    public static void writeToStream(String content, OutputStream stream, int width, int height) throws WriterException, IOException {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, format, stream);
    }

    /**
     * 生成二維碼圖片文件
     * @param content 二維碼內(nèi)容
     * @param path    文件保存路徑
     * @param width   寬
     * @param height  高
     */
    public static void createQRCode(String content, String path, int width, int height) throws WriterException, IOException {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        //toPath() 方法由 jdk1.7 及以上提供
        MatrixToImageWriter.writeToPath(bitMatrix, format, new File(path).toPath());
    }


}

maven 依賴

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

package com.kaishengit;

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 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Hashtable;

public class Test {

    public static void main(String[] args) throws IOException {

        String text = "www.baidu.com";
        int width = 100;
        int height = 100;
        String format = "png";
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            Path file = new File("D:/new.png").toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file);
        } catch (WriterException e) {
      // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //解析二維碼
        resolve();


    }

    private static void resolve() {
        MultiFormatReader formatReader = new MultiFormatReader();
        File file = new File("D:/new.png");
        BufferedImage image = null;
        try {
            image = ImageIO.read(file);
        } catch (IOException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        Result result = null;
        try {
            result = formatReader.decode(binaryBitmap, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        System.err.println("解析結(jié)果:" + result.toString());
        System.out.println(result.getBarcodeFormat());
        System.out.println(result.getText());
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子蜘腌,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,997評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件踏志,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡胀瞪,警方通過(guò)查閱死者的電腦和手機(jī)针余,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,603評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)凄诞,“玉大人圆雁,你說(shuō)我怎么就攤上這事》” “怎么了伪朽?”我有些...
    開(kāi)封第一講書人閱讀 163,359評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)汛蝙。 經(jīng)常有香客問(wèn)我烈涮,道長(zhǎng),這世上最難降的妖魔是什么窖剑? 我笑而不...
    開(kāi)封第一講書人閱讀 58,309評(píng)論 1 292
  • 正文 為了忘掉前任坚洽,我火速辦了婚禮,結(jié)果婚禮上西土,老公的妹妹穿的比我還像新娘酪术。我一直安慰自己,他們只是感情好翠储,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,346評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布绘雁。 她就那樣靜靜地躺著,像睡著了一般援所。 火紅的嫁衣襯著肌膚如雪庐舟。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,258評(píng)論 1 300
  • 那天住拭,我揣著相機(jī)與錄音挪略,去河邊找鬼历帚。 笑死,一個(gè)胖子當(dāng)著我的面吹牛杠娱,可吹牛的內(nèi)容都是我干的挽牢。 我是一名探鬼主播,決...
    沈念sama閱讀 40,122評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼摊求,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼禽拔!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起室叉,我...
    開(kāi)封第一講書人閱讀 38,970評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤睹栖,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后茧痕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體野来,經(jīng)...
    沈念sama閱讀 45,403評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,596評(píng)論 3 334
  • 正文 我和宋清朗相戀三年踪旷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了曼氛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,769評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡令野,死狀恐怖舀患,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情彩掐,我是刑警寧澤,帶...
    沈念sama閱讀 35,464評(píng)論 5 344
  • 正文 年R本政府宣布灰追,位于F島的核電站堵幽,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏弹澎。R本人自食惡果不足惜朴下,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,075評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望苦蒿。 院中可真熱鬧殴胧,春花似錦、人聲如沸佩迟。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,705評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)报强。三九已至灸姊,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間秉溉,已是汗流浹背力惯。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,848評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工碗誉, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人父晶。 一個(gè)月前我還...
    沈念sama閱讀 47,831評(píng)論 2 370
  • 正文 我出身青樓哮缺,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親甲喝。 傳聞我的和親對(duì)象是個(gè)殘疾皇子尝苇,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,678評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)試測(cè)...
    七魂之月閱讀 892評(píng)論 1 16
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)俺猿,斷路器茎匠,智...
    卡卡羅2017閱讀 134,654評(píng)論 18 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,095評(píng)論 25 707
  • 1 h是我一好哥們,我們呢就是臭味相同押袍,都是小孩子脾氣诵冒,一言不合就翻臉那種渣男。h和現(xiàn)在的女票z在一起谊惭,是因?yàn)閔和...
    肖輝閱讀 279評(píng)論 0 0
  • 用心地去感受生活吧汽馋,因?yàn)椋恳环N生活圈盔,對(duì)我們來(lái)說(shuō)都是限量版豹芯。 抓住每一個(gè)確幸的瞬間,讓我們感恩生活驱敲,用心經(jīng)營(yíng)铁蹈。 1...
    夏玫小墨閱讀 391評(píng)論 2 5