java程序员菜鸟进阶六之二维码生成与解析

一、概述

二维条码/二维码是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息的;在代码编制上巧妙地利用构成计算机内部逻辑基础的“0”、“1”比特流的概念,使用若干个与二进制相对应的几何形体来表示文字数值信息,通过图象输入设备或光电扫描设备自动识读以实现信息自动处理:它具有条码技术的一些共性:每种码制有其特定的字符集;每个字符占有一定的宽度;具有一定的校验功能等。同时还具有对不同行的信息自动识别功能、及处理图形旋转变化点。

二、java代码生成二维码与解析二维码

1、谷歌的zxing包的使用

2、代码

package com.centaline.controller;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.EnumMap;

import javax.imageio.ImageIO;

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.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class zxingTest {

	//二维码颜色
	private static final int BLACK = 0xFF000000;
	//二维码背景颜色
	private static final int WHITE = 0xFFFFFFFF;
	//二维码宽度
	private static final int width = 300;
	//二维码高度
	private static final int height = 300;
	
	private static final EnumMap hints
	        = new EnumMap(EncodeHintType.class);
	private static final EnumMap hints2 = new EnumMap(DecodeHintType.class);  
	static{  
		hints2.put(DecodeHintType.CHARACTER_SET, "UTF-8");  
	}  
	//二维码格式参数
	static{
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //二维码纠错级别
        hints.put(EncodeHintType.MARGIN, 1); //二维码空白边界大小 
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
        hints.put(EncodeHintType.MAX_SIZE, 350);  
        hints.put(EncodeHintType.MIN_SIZE, 150);
	}
	
	
	/**
	 * 绘制二维码
	 * @param contents二维码内容
	 * @return image二维码图片
	 */
	public static BufferedImage encodeImg(String contents){  
        BufferedImage image = null;  
        try{  
            BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);  
            image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
            int width = matrix.getWidth();  
            int height = matrix.getHeight();  
            for(int x = 0; x < width; x++){  
                for(int y =0;y < height; y++){  
                    image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
                }  
            }  
        }catch(Exception e){  
            System.out.println("生成二维码失败"+e.getMessage());  
        }  
        return image;  
    } 
	
	
	/**
	 * 二维码输出到文件夹
	 * @param contents二维码内容
	 * @param format图片格式
	 * @param file文件
	 */
	public static void writeToFile(String contents,String format,File file){  
        BufferedImage image = encodeImg(contents);  
        try {  
            ImageIO.write(image, format, file);  
        } catch (IOException e) {  
            System.out.println("二维码写入文件失败"+e.getMessage());  
        }  
    } 
	
	
	/**
	 * 二维码流式输出
	 * @param contents二维码内容
	 * @param format图片格式
	 * @param stream输出
	 */
	public static void writeToStream(String contents,String format,OutputStream stream){  
        BufferedImage image = encodeImg(contents);  
        try {  
            ImageIO.write(image, format, stream);  
        } catch (IOException e) {  
            System.out.println("二维码写入流失败"+e.getMessage());  
        }  
    } 
	
	
	
    /**
     * 二维码解析
     * @param imgFile文件类
     * @return
     */
    public static String decodeImg(File imgFile){  
        String content = null;  
        if(!imgFile.isFile()){  
            System.out.println("输入非文件");  
            return null;  
        }  
        try {  
            BufferedImage image = ImageIO.read(imgFile);  
            LuminanceSource source = new BufferedImageLuminanceSource(image);  
            Binarizer binarizer = new HybridBinarizer(source);  
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);  
            MultiFormatReader reader = new MultiFormatReader();  
            Result result = reader.decode(binaryBitmap, hints2);  
            content = result.getText();  
        } catch (NotFoundException e) {  
            System.out.println("二维码解析NotFoundException");  
            e.printStackTrace();  
        } catch (IOException e) {  
            System.out.println("二维码解析IOException");  
            e.printStackTrace();  
        }  
        return content;  
    }  
	
    
    
    /** 
     * 二维码绘制logo 
     * @param twodimensioncodeImg 二维码图片文件 
     * @param logoImg logo图片文件 
     * */  
    public static BufferedImage encodeImgLogo(File twodimensioncodeImg,File logoImg){  
        BufferedImage twodimensioncode = null;  
        try{  
            if(!twodimensioncodeImg.isFile() || !logoImg.isFile()){  
                System.out.println("输入非图片");  
                return null;  
            }  
            //读取二维码图片  
            twodimensioncode = ImageIO.read(twodimensioncodeImg);  
            //获取画笔  
            Graphics2D g = twodimensioncode.createGraphics();  
            //读取logo图片  
            BufferedImage logo = ImageIO.read(logoImg);  
            //设置二维码logo大小,太大,会覆盖二维码,此处20%  
            int logoWidth = logo.getWidth(null) > twodimensioncode.getWidth()*2 /10 ? (twodimensioncode.getWidth()*2 /10) : logo.getWidth(null);  
            int logoHeight = logo.getHeight(null) > twodimensioncode.getHeight()*2 /10 ? (twodimensioncode.getHeight()*2 /10) : logo.getHeight(null);  
            //设置logo图片放置位置  
            //中心  
            int x = (twodimensioncode.getWidth() - logoWidth) / 2;  
            int y = (twodimensioncode.getHeight() - logoHeight) / 2;  
            //右下角,15为调整值  
//          int x = twodimensioncode.getWidth()  - logoWidth-15;  
//          int y = twodimensioncode.getHeight() - logoHeight-15;  
            //开始合并绘制图片  
            g.drawImage(logo, x, y, logoWidth, logoHeight, null);  
            g.drawRoundRect(x, y, logoWidth, logoHeight, 15 ,15);  
            //logo边框大小  
            g.setStroke(new BasicStroke(2));  
            //logo边框颜色  
            g.setColor(Color.WHITE);  
            g.drawRect(x, y, logoWidth, logoHeight);  
            g.dispose();  
            logo.flush();  
            twodimensioncode.flush();  
        }catch(Exception e){  
            System.out.println("二维码绘制logo失败");  
        }  
        return twodimensioncode;  
    }  
      
    /** 
     * 二维码输出到文件 
     * @param twodimensioncodeImg 二维码图片文件 
     * @param logoImg logo图片文件 
     * @param format 图片格式 
     * @param file 输出文件 
     * */  
    public static void writeToFile(File twodimensioncodeImg,File logoImg,String format,File file){  
        BufferedImage image = encodeImgLogo(twodimensioncodeImg, logoImg);  
        try {  
            ImageIO.write(image, format, file);  
        } catch (IOException e) {  
            System.out.println("二维码写入文件失败"+e.getMessage());  
        }  
    }
    
    
    /** 
     * 二维码流式输出 
     * @param twodimensioncodeImg 二维码图片文件 
     * @param logoImg logo图片文件 
     * @param format 图片格式 
     * @param stream 输出流 
     * */  
    public static void writeToStream(File twodimensioncodeImg,File logoImg,String format,OutputStream stream){  
        BufferedImage image = encodeImgLogo(twodimensioncodeImg, logoImg);  
        try {  
            ImageIO.write(image, format, stream);  
        } catch (IOException e) {  
            System.out.println("二维码写入流失败"+e.getMessage());  
        }  
    }  
    
        
    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
    	String contents = "http://www.baidu.com";  
    	String format = "jpg"; //***此处如果格式为"gif",则logo图片为黑色,其他格式ok  
    	//生成二维码  
    	File logoImg = new File("D:"+File.separator+"logo.jpg");  
    	File img = new File("D:"+File.separator+"csdn.jpg");  
    	writeToFile(contents, format, img);  
        //添加logo图片  
    	File img1 = new File("D:"+File.separator+"csdnlogo.jpg");  
    	writeToFile(img, logoImg, format, img1);  
    	
    	//解析二维码  
    	String content = decodeImg(img);  
    	System.out.println("1:"+content);  
    	//带logo  
    	String content1 = decodeImg(img1);  
    	System.out.println("2:"+content1);  
    }
    	
}

三、js方式生成二维码

1、QRCode.js 是一个用于生成二维码的 JavaScript 库。主要是通过获取 DOM 的标签,再通过 HTML5 Canvas 绘制而成,不依赖任何库。

2、代码




JS生成二维码示例







你可能感兴趣的:(web开发进阶)