java二维码开发

    之前就写过很多关于二维码的东西,一直没有时间整理一下,所以呢今天就先来介绍一下如何利用java开发二维码。生成二维码有很多jar包可以实现,例如Zxing,QRcode,前者是谷歌的,后者日本的,这里我将对这两种方式的具体实现方法做简单介绍。

一、二维码的原理

         二维条形码最早发明于日本,它是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的,在代码编制上巧妙地利用构成计算机内部逻辑基础的“0”、“1”比特流的概念,使用若干个与二进制相对应的几何形体来表示文字数值信息,通过图象输入设备或光电扫描设备自动识读以实现信息自动处理。

 

二、具体实现

  1.QRcode

     (1).获取QRcode.jar, 下载链接:http://www.swetake.com/qrcode/java/qr_java.html (官网)

                                                   http://download.csdn.net/download/xch_yang/9514836

     (2).将jar包添加进项目的构建路径(将jar包复制到项目下,右键:构建路径--添加至构建路径)。

 

  代码如下

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.imageio.ImageIO;
import com.swetake.util.Qrcode;

public class QrcodeImg {
    /**
     * 生成二维码图片
     * @author 杨雄超
     * @param content 二维码内容
     * @param imgPath 二维码图片的保存路径
     */
    public static void getQrcodeImg(String content,String imgPath){
        int width=140;
        int height=140;
        //实例化Qrcode
        Qrcode qrcode=new Qrcode();
        //设置二维码的排错率L(7%) M(15%) Q(25%) H(35%)
        qrcode.setQrcodeErrorCorrect('M');
        qrcode.setQrcodeEncodeMode('B');        
        //设置二维码尺寸(1~49)
        qrcode.setQrcodeVersion(7);
        //设置图片尺寸
        BufferedImage bufImg=new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        
        //绘制二维码图片
        Graphics2D gs=bufImg.createGraphics();
        //设置二维码背景颜色
        gs.setBackground(Color.WHITE);
        //创建一个矩形区域
        gs.clearRect(0, 0, width, height);
        //设置二维码的图片颜色值 黑色
        gs.setColor(Color.BLACK);
        
        //获取内容的字节数组,设置编码集
        try {
            byte[] contentBytes=content.getBytes("utf-8");
            int pixoff=2;
            //输出二维码
            if(contentBytes.length>0&&contentBytes.length<120){
                boolean[][] codeOut=qrcode.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);
                        }
                    }
                }    
            }
            gs.dispose();
            bufImg.flush();
            //生成二维码图片
            File imgFile=new File(imgPath);
            ImageIO.write(bufImg, "png", imgFile);
            
            System.out.println("二维码生成成功!");
            
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

    public static void main(String[] args) {
        getQrcodeImg("http://m.55bbs.com/liren_2003609/", "E:\\test.png");
    }
}

结果:内容为网页图片的链接,所以扫描之后结果如图,当然,你可以将内容换成文字。

                    

 

 

 

 2.ZXing

   (1).获取ZXing包, 下载链接:http://download.csdn.net/detail/xch_yang/9514956

   (2)这里我们只需要Zxing包中的core-3.0.0.jar,所以将core-3.0.0.jar添加至构建路径。

 

 实现代码:

  创建类:ImageWrite(二维码的生成需要借助这个类)

import javax.imageio.ImageIO; 
import java.io.File; 
import java.io.OutputStream; 
import java.io.IOException;   
import java.awt.image.BufferedImage; 
public final class ImageWrite {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
    private ImageWrite() {}
    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);  
        }   
    }  
}

 

  创建类:QRcodeEncode

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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 QRcodeEncode {

    public static void main(String[] args) {
        try {
            //二维码内容
            String content = "Hello QRcode!";
            //二维码生成路径
            String path = "F:/java workspace";   
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); 
            Map hints = new HashMap();     
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400,hints);   
            File file1 = new File(path,"test.jpg"); 
            ImageWrite.writeToFile(bitMatrix, "jpg", file1);
            System.out.println("二维码已生成!");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriterException e) {
            e.printStackTrace();
        } 
    }
}

 

结果:二维码图片所在位置:F:/java workspace/test.jpg    扫描内容:Hello QRcode!

        

  这里简单的介绍了利用java开发二维码的两种方式,当然还可以向二维码中添加logo,实现方式后续介绍。

   

 

 


更多技术干货,欢迎关注我的公众号:ChaoYoung

猜你喜欢

转载自blog.csdn.net/xch_yang/article/details/51373384