码迷,mamicode.com
首页 > 其他好文 > 详细

QR Code

时间:2016-08-01 13:47:33      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

  二维码的生成

 

本文记录了三种生成二维码的方式,Java后台生成、jquery生成、js生成

Java后台生成比较浪费资源

Jquery canvas生成模式需要浏览器支持h5,table生成的二维码存在宽高不等

Js生成的二维码暂时未发现不妥之处

建议使用js生成,引用qrcode一个js插件即可。

1.      Java生成

1、获取jar包支持pom.xml

        <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> 

2、 思路:

1、  获取需要生成二维码的内容

2、  定义需要生成图片格式、宽度、高度、以及白边的宽度

3、  转流

4、  画图

3、代码

package com.maociyuan.cnblogs.home.service.qrcode;

 

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.io.OutputStream;

import java.util.HashMap;

import java.util.Hashtable;

import java.util.Map;

 

import javax.imageio.ImageIO;

 

import com.google.zxing.BarcodeFormat;

import com.google.zxing.EncodeHintType;

import com.google.zxing.MultiFormatWriter;

import com.google.zxing.common.BitMatrix;

 

public class QRCodeService {

    private static final int BLACK = 0xff000000;

    private static final int WHITE = 0xFFFFFFFF;

 

    /**

     * 生成QRCode二维码<br>

     * 在编码时需要将com.google.zxing.qrcode.encoder.Encoder.java中的<br>

     * static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br>

     * 修改为UTF-8,否则中文编译后解析不了<br>

     */

    public BufferedImage encode(String contents, int width, int height) {

        BufferedImage bi = null;

        try {

            Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();

            hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码

            hints.put(EncodeHintType.MARGIN, 0);

            BitMatrix bitMatrix =

                    new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height,

                            hints);

            int margin = 5; // 自定义白边边框宽度

            bitMatrix = updateBit(bitMatrix, margin); // 生成新的bitMatrix

            // 因为二维码生成时,白边无法控制,去掉原有的白边,再添加自定义白边后,二维码大小与size大小就存在差异了,为了让新生成的二维码大小还是size大小,根据size重新生成图片

            bi = toBufferedImage(bitMatrix);

            bi = zoomInImage(bi, width, height);// 根据size放大、缩小生成的二维码片

            /*

             * BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, format, width,

             * height); writeToFile(bitMatrix, "jpg", file);

             */

        } catch (Exception e) {

            e.printStackTrace();

        }

        return bi;

    }

 

    /**

     * 生成二维码图片<br>

     *

     * @param matrix

     * @param format 图片格式

     * @param file 生成二维码图片位置

     * @throws IOException

     */

 

    public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {

        BufferedImage image = toBufferedImage(matrix);

        if (!ImageIO.write(image, format, file)) {

            throw new IOException("Could not write an image of format " + format + " to " + file);

        }

    }

 

    /**

     * 生成二维码图片<br>

     *

     * @param matrix

     * @param format 图片格式

     * @param stream 生成二维码图片輸出流

     * @throws IOException

     */

    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)

            throws IOException {

        BufferedImage image = toBufferedImage(matrix);

        if (!ImageIO.write(image, format, stream)) {

            throw new IOException("Could not write an image of format " + format);

        }

    }

 

    /**

     * 生成二维码内容<br>

     *

     * @param matrix

     * @return

     */

    public static BufferedImage toBufferedImage(BitMatrix matrix) {

        int width = matrix.getWidth();

        int height = matrix.getHeight();

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {

            for (int y = 0; y < height; y++) {

                image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);

            }

        }

        return image;

    }

 

    private static BitMatrix updateBit(BitMatrix matrix, int margin) {

        int tempM = margin * 2;

        int[] rec = matrix.getEnclosingRectangle(); // 获取二维码图案的属性

        int resWidth = rec[2] + tempM;

        int resHeight = rec[3] + tempM;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); // 按照自定义边框生成新的BitMatrix

        resMatrix.clear();

        for (int i = margin; i < resWidth - margin; i++) { // 循环,将二维码图案绘制到新的bitMatrix中

            for (int j = margin; j < resHeight - margin; j++) {

                if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {

                    resMatrix.set(i, j);

                }

            }

        }

        return resMatrix;

    }

 

    public static BufferedImage zoomInImage(BufferedImage originalImage, int width, int height) {

        BufferedImage newImage = new BufferedImage(width, height, originalImage.getType());

        Graphics g = newImage.getGraphics();

        g.drawImage(originalImage, 0, 0, width, height, null);

        g.dispose();

        return newImage;

    }

 

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

        String text = "http://www.cnblogs.com/maociyuan/"; // 二维码内容

        int width = 150; // 二维码图片宽度

        int height = 150; // 二维码图片高度

        String format = "jpg";// 二维码的图片格式

 

        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();

        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码

        hints.put(EncodeHintType.MARGIN, 0);

 

        BitMatrix bitMatrix =

                new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        int margin = 5; // 自定义白边边框宽度

        bitMatrix = updateBit(bitMatrix, margin); // 生成新的bitMatrix

        // 因为二维码生成时,白边无法控制,去掉原有的白边,再添加自定义白边后,二维码大小与size大小就存在差异了,为了让新生成的二维码大小还是size大小,根据size重新生成图片

        BufferedImage bi = toBufferedImage(bitMatrix);

        bi = zoomInImage(bi, width, height);// 根据size放大、缩小生成的二维码片

        // 生成二维码

        File outputFile = new File("d:" + File.separator + "new.jpg");

        ImageIO.write(bi, "png", outputFile); // 生成二维码图

        writeToFile(bitMatrix, format, outputFile);

    }

}

2.      Jquery生成

1、加载jquery.qrcode.js、jquery.min.js

2、创建一个用于包含 QRcode 图片的 DOM 元素,比如 div:

        <div id="qrcode"></div>

3、通过下面代码生成QRcode 分table和canvas

$(‘#qrcodeTable‘).qrcode({ 

                            render  : "table", 

                            width:150,

                            height:150,

                            text    : “http://www.cnblogs.com/maociyuan/”

                   });

        

                            $(‘#qrcodeCanvas‘).qrcode({ 

                            render  : "canvas",

                            width:150,

                            height:150,

                            text    : “http://www.cnblogs.com/maociyuan/”

                   });

3.      Js生成

1、加载qrcode.js

2、创建一个用于包含 QRcode 图片的 DOM 元素,比如 div:

        <div id="qrcode"></div>

3、然后通过下面代码生成 QRcode:

var qrcode = new QRCode(document.getElementById("qrcode"), {

                   width : 150,

                   height : 150

         });

qrcode.makeCode("http://www.cnblogs.com/maociyuan/");

 

4.      jquery、js生成二维码实例

<html> 

<head> 

<title>QRCode generator</title> 

<style>

         .inputdiv{

                            position: absolute;

                            left: 40%;

                            top: 20%;

                            width:200px;

                            height:200px;

                            margin-left:-100px;

                            margin-top:-100px;

         }

         .qrcode{

                            position: absolute;

                            left: 45%;

                            top: 25%;

                            width:200px;

                            height:200px;

                            margin-left:-100px;

                            margin-top:-100px;

         }

</style>

</head> 

<body> 

<script type="text/javascript" src="jquery.min.js"></script>

<script type="text/javascript" src="jquery.qrcode.min.js"></script>

<script type="text/javascript" src="qrcode.js"></script>

<div class="inputdiv">

                   <input id="text" type="text" value="http://www.cnblogs.com/maociyuan/你大爷" style="width:500px;"></input>

</div> 

<div class ="qrcode">

<p>二维码:table 高度:<span id="heightTable"></span></p> 

<div id="qrcodeTable"></div> 

<p>二维码:canvas 高度:<span id="heightCanvas"></span></p>  

<div id="qrcodeCanvas"></div> 

<p>二维码:js 高度:<span id="heightJsQrcode"></span></p>

<div id="qrcode"></div>

</div>

<script> 

         function qrcodeTable(){

                   var elText = document.getElementById("text").value;

 

                   if (!elText) {

                            alert("Input a text");

                            elText.focus();

                            return;

                   }

                   $(‘#qrcodeTable‘).empty();

                   $(‘#qrcodeTable‘).qrcode({ 

                            render  : "table", 

                            width:150,

                            height:150,

                            text    : elText

                   });

                   $("#heightTable").text($("#qrcodeTable").height());

         } 

         function qrcodeCanvas(){

                   var elText = document.getElementById("text").value;

        

                   if (!elText) {

                            alert("Input a text");

                            elText.focus();

                            return;

                   }

                   $(‘#qrcodeCanvas‘).empty();

                   $(‘#qrcodeCanvas‘).qrcode({ 

                            render  : "table", 

                            width:150,

                            height:150,

                            text    : elText

                   });

                   $("#heightCanvas").text($("#qrcodeTable").height());

         } 

 

         var qrcode = new QRCode(document.getElementById("qrcode"), {

                   width : 150,

                   height : 150

         });

 

 

         function makeCode () {             

                   var elText = document.getElementById("text");

                  

                   if (!elText.value) {

                            alert("Input a text");

                            elText.focus();

                            return;

                   }

                  

                   qrcode.makeCode(elText.value);

                   $("#heightJsQrcode").text($("#qrcode").height());

         }

 

         makeCode();

         qrcodeTable();

         qrcodeCanvas();

 

$("#text").

         on("blur", function () {

                   makeCode();

                   qrcodeTable();

                   qrcodeCanvas();

         }).

         on("keydown", function (e) {

                   if (e.keyCode == 13) {

                            makeCode();

                            qrcodeTable();

                            qrcodeCanvas();

                   }

         });

</script> 

 

</body> 

</html>

 

 

附一个转utf-8的js函数

function toUtf8(str) {    
    var out, i, len, c;    
    out = "";    
    len = str.length;    
    for(i = 0; i < len; i++) {    
        c = str.charCodeAt(i);    
        if ((c >= 0x0001) && (c <= 0x007F)) {    
            out += str.charAt(i);    
        } else if (c > 0x07FF) {    
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));    
            out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));    
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));    
        } else {    
            out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));    
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));    
        }    
    }    
    return out;    

 

参考资料

https://github.com/jeromeetienne/jquery-qrcode

http://happyqing.iteye.com/blog/2292524

QR Code

标签:

原文地址:http://www.cnblogs.com/maociyuan/p/5725411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!