二维码生成软件|java生成二维码的几种实现方便及实例

更新时间:2019-11-29    来源:代码生成    手机版     字体:

【www.bbyears.com--代码生成】

先我们来看一个直接用java代码生成二维码的实例。

Java代码

package foo;  
   
public class App {  
    public static void main(String[] args) {    
        String imgPath = "O:/erweima/fanglei@nannan.jpg";    
        String encoderContent = "Hello,world!";    
        TwoDimensionCode handler = new TwoDimensionCode();    
        handler.encoderQRCode(encoderContent, imgPath, "png");    
        System.out.println("========encoder success");    
        String decoderContent = handler.decoderQRCode(imgPath);    
        System.out.println(decoderContent);    
        System.out.println("========decoder success!!!");    
        }    
}




二维码生成帮助类

package foo;  
   
import java.awt.Color;  
import java.awt.Graphics2D;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
   
import javax.imageio.ImageIO;  
   
import jp.sourceforge.qrcode.QRCodeDecoder;  
import jp.sourceforge.qrcode.exception.DecodingFailedException;  
   
import com.swetake.util.Qrcode;  
   
public class TwoDimensionCode {    
       
    /**  
     * 生成二维码(QRCode)图片  
     * @param content 存储内容  
     * @param imgPath 图片路径  
     */   
    public void encoderQRCode(String content, String imgPath) {    
        this.encoderQRCode(content, imgPath, "png", 7);    
    }    
         
    /**  
     * 生成二维码(QRCode)图片  
     * @param content 存储内容  
     * @param output 输出流  
     */   
    public void encoderQRCode(String content, OutputStream output) {    
        this.encoderQRCode(content, output, "png", 7);    
    }    
         
    /**  
     * 生成二维码(QRCode)图片  
     * @param content 存储内容  
     * @param imgPath 图片路径  
     * @param imgType 图片类型  
     */   
    public void encoderQRCode(String content, String imgPath, String imgType) {    
        this.encoderQRCode(content, imgPath, imgType, 7);    
    }    
         
    /**  
     * 生成二维码(QRCode)图片  
     * @param content 存储内容  
     * @param output 输出流  
     * @param imgType 图片类型  
     */   
    public void encoderQRCode(String content, OutputStream output, String imgType) {    
        this.encoderQRCode(content, output, imgType, 7);    
    }    
     
    /**  
     * 生成二维码(QRCode)图片  
     * @param content 存储内容  
     * @param imgPath 图片路径  
     * @param imgType 图片类型  
     * @param size 二维码尺寸  
     */   
    public void encoderQRCode(String content, String imgPath, String imgType, int size) {    
        try {    
            BufferedImage bufImg = this.qRCodeCommon(content, imgType, size);    
                 
            File imgFile = new File(imgPath);    
            // 生成二维码QRCode图片    
            ImageIO.write(bufImg, imgType, imgFile);    
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
    }    
     
    /**  
     * 生成二维码(QRCode)图片  
     * @param content 存储内容  
     * @param output 输出流  
     * @param imgType 图片类型  
     * @param size 二维码尺寸  
     */   
    public void encoderQRCode(String content, OutputStream output, String imgType, int size) {    
        try {    
            BufferedImage bufImg = this.qRCodeCommon(content, imgType, size);    
            // 生成二维码QRCode图片    
            ImageIO.write(bufImg, imgType, output);    
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
    }    
         
    /**  
     * 生成二维码(QRCode)图片的公共方法  
     * @param content 存储内容  
     * @param imgType 图片类型  
     * @param size 二维码尺寸  
     * @return  
     */   
    private BufferedImage qRCodeCommon(String content, String imgType, int size) {    
        BufferedImage bufImg = null;    
        try {    
            Qrcode qrcodeHandler = new Qrcode();    
            // 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小    
            qrcodeHandler.setQrcodeErrorCorrect('M');    
            qrcodeHandler.setQrcodeEncodeMode('B');    
            // 设置设置二维码尺寸,取值范围1-40,值越大尺寸越大,可存储的信息越大    
            qrcodeHandler.setQrcodeVersion(size);    
            // 获得内容的字节数组,设置编码格式    
            byte[] contentBytes = content.getBytes("utf-8");    
            // 图片尺寸    
            int imgSize = 67 + 12 * (size - 1);    
            bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);    
            Graphics2D gs = bufImg.createGraphics();    
            // 设置背景颜色    
            gs.setBackground(Color.WHITE);    
            gs.clearRect(0, 0, imgSize, imgSize);    
     
            // 设定图像颜色> BLACK    
            gs.setColor(Color.BLACK);    
            // 设置偏移量,不设置可能导致解析出错    
            int pixoff = 2;    
            // 输出内容> 二维码    
            if (contentBytes.length > 0 && contentBytes.length < 800) {    
                boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);    
                for (int i = 0; i < codeOut.length; i++) {    
                    for (int j = 0; j < codeOut.length; j++) {    
                        if (codeOut[j][i]) {    
                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);    
                        }    
                    }    
                }    
            } else {    
                throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");    
            }    
            gs.dispose();    
            bufImg.flush();    
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
        return bufImg;    
    }    
         
    /**  
     * 解析二维码(QRCode)  
     * @param imgPath 图片路径  
     * @return  
     */   
    public String decoderQRCode(String imgPath) {    
        // QRCode 二维码图片的文件    
        File imageFile = new File(imgPath);    
        BufferedImage bufImg = null;    
        String content = null;    
        try {    
            bufImg = ImageIO.read(imageFile);    
            QRCodeDecoder decoder = new QRCodeDecoder();    
            content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");     
        } catch (IOException e) {    
            System.out.println("Error: " + e.getMessage());    
            e.printStackTrace();    
        } catch (DecodingFailedException dfe) {    
            System.out.println("Error: " + dfe.getMessage());    
            dfe.printStackTrace();    
        }    
        return content;    
    }    
         
    /**  
     * 解析二维码(QRCode)  
     * @param input 输入流  
     * @return  
     */   
    public String decoderQRCode(InputStream input) {    
        BufferedImage bufImg = null;    
        String content = null;    
        try {    
            bufImg = ImageIO.read(input);    
            QRCodeDecoder decoder = new QRCodeDecoder();    
            content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");     
        } catch (IOException e) {    
            System.out.println("Error: " + e.getMessage());    
            e.printStackTrace();    
        } catch (DecodingFailedException dfe) {    
            System.out.println("Error: " + dfe.getMessage());    
            dfe.printStackTrace();    
        }    
        return content;    
    }    
     
}



二维码生成帮助类

package foo;  
   
import java.awt.image.BufferedImage;  
   
import jp.sourceforge.qrcode.data.QRCodeImage;  
   
public class TwoDimensionCodeImage implements QRCodeImage {    
         
    BufferedImage bufImg;    
         
    public TwoDimensionCodeImage(BufferedImage bufImg) {    
        this.bufImg = bufImg;    
    }  
   
    public int getHeight() {  
        // TODO Auto-generated method stub  
        return 0;  
    }  
   
    public int getPixel(int arg0, int arg1) {  
        // TODO Auto-generated method stub  
        return 0;  
    }  
   
    public int getWidth() {  
        // TODO Auto-generated method stub  
        return 0;  
    }    
}





java实现二维码生成的几个方法

1: 使用SwetakeQRCode在Java项目中生成二维码
http://swetake.com/qr/ 下载地址
或着http://sourceforge.jp/projects/qrcode/downloads/28391/qrcode.zip
这个是日本人写的,生成的是我们常见的方形的二维码
可以用中文

如:5677777ghjjjjj

2: 使用BarCode4j生成条形码和二维码
BarCode4j网址:http://sourceforge.net/projects/barcode4j/

barcode4j是使用datamatrix的二维码生成算法,为支持qr的算法
datamatrix是欧美的标准,qr为日本的标准,
barcode4j一般生成出来是长方形的

如:88777alec000yan
这个博客这方面说的挺清楚的:
http://baijinshan.iteye.com/blog/1004554

3:zxing
zxing 这个是google的
下载地址
http://code.google.com/p/zxing/downloads/list

Java代码:

import java.io.File;   
import java.util.Hashtable;   
 
import com.google.zxing.BarcodeFormat;   
import com.google.zxing.EncodeHintType;   
import com.google.zxing.MultiFormatWriter;   
import com.google.zxing.client.j2se.MatrixToImageWriter;   
import com.google.zxing.common.BitMatrix;   
import com.google.zxing.qrcode.QRCodeWriter;   
 
 
 
public class QRCodeEvents {   
       
    public static void main(String []args)throws Exception{   
        String text = "你好";   
        int width = 100;   
        int height = 100;   
        String format = "png";   
        Hashtable hints= new Hashtable();   
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");   
         BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height,hints);   
         File outputFile = new File("new.png");   
         MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);   
            
    }   
}  

4:google chart api就有实现二维码的方法

    利用这个api,使用google appengine进行实现。

 

5:JS生成二维码

使用jquery-qrcode生成二维码

先简单说一下jquery-qrcode,这个开源的三方库(可以从https://github.com/jeromeetienne/jquery-qrcode 获取),

qrcode.js 是实现二维码数据计算的核心类,

jquery.qrcode.js 是把它用jquery方式封装起来的,用它来实现图形渲染,其实就是画图(支持canvas和table两种方式)


支持的功能主要有:

Js代码:

    text     : "https://github.com/jeromeetienne/jquery-qrcode"  //设置二维码内容  

     

Js代码:

    render   : "canvas",//设置渲染方式   
    width       : 256,     //设置宽度   
    height      : 256,     //设置高度   
    typeNumber  : -1,      //计算模式   
    correctLevel    : QRErrorCorrectLevel.H,//纠错等级   
    background      : "#ffffff",//背景颜色   
    foreground      : "#000000" //前景颜色



使用方式非常简单

 

Js代码:

    jQuery('#output').qrcode({width:200,height:200,correctLevel:0,text:content});  

经过简单实践,

使用canvas方式渲染性能还是非常不错的,但是如果用table方式,性能不太理想,特别是IE9以下的浏览器,所以需要自行优化一下渲染table的方式,这里就不细述了。

其实上面的js有一个小小的缺点,就是默认不支持中文。

这跟js的机制有关系,jquery-qrcode这个库是采用 charCodeAt() 这个方式进行编码转换的,

而这个方法默认会获取它的 Unicode 编码,一般的解码器都是采用UTF-8, ISO-8859-1等方式,

英文是没有问题,如果是中文,一般情况下Unicode是UTF-16实现,长度2位,而UTF-8编码是3位,这样二维码的编解码就不匹配了。

 

解决方式当然是,在二维码编码前把字符串转换成UTF-8,具体代码如下:

function utf16to8(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;   
}




Java用zxing开发包生成二维码实例

1.java这边的话生成二维码有很多开发的jar包如zxing,qrcode.q前者是谷歌开发的后者则是小日本开发的,这里的话我使用zxing的开发包来弄

2.先下载zxing开发包,这里用到的只是core那个jar包

3.使用zxing开发还需要一个类,代码如下

package org.lxh; 
import com.google.zxing.common.BitMatrix; 
    
 import javax.imageio.ImageIO; 
 import java.io.File; 
 import java.io.OutputStream; 
 import java.io.IOException; 
 import java.awt.image.BufferedImage; 
    
    
 public final class MatrixToImageWriter { 
    
   private static final int BLACK = 0xFF000000; 
   private static final int WHITE = 0xFFFFFFFF; 
    
   private MatrixToImageWriter() {} 
    
      
   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) ? BLACK : WHITE); 
       } 
     } 
     return image; 
   } 
    
      
   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); 
     } 
   } 
    
      
   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); 
     } 
   } 
    
 }


 
4.借助上面的类生成二维码

package org.lxh; 
   
import java.io.File; 
import java.util.Hashtable; 
   
import com.google.zxing.BarcodeFormat; 
import com.google.zxing.EncodeHintType; 
import com.google.zxing.MultiFormatWriter; 
import com.google.zxing.WriterException; 
import com.google.zxing.common.BitMatrix; 
   
public class Test { 
   
    /**
     * @param args
     * @throws Exception 
     */ 
    public static void main(String[] args) throws Exception { 
        String text = "http://www.baidu.com"; 
        int width = 300; 
        int height = 300; 
        //二维码的图片格式 
        String format = "gif"; 
        Hashtable hints = new Hashtable(); 
        //内容所使用编码 
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, 
                BarcodeFormat.QR_CODE, width, height, hints); 
        //生成二维码 
        File outputFile = new File("d:"+File.separator+"new.gif"); 
        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile); 
   
    } 
   
}



text就是二维码的内容,这里可以使普通的文字也可以是链接,是不是没有想象中那么难呢?

本文来源:http://www.bbyears.com/wangyetexiao/81342.html

热门标签

更多>>

本类排行