二维码之java实现

二维码的简介


二维码 (2-dimensional bar code),是用某种特定的几何图形按一定规律在平面(二维方向上)
分布的黑白相间的图形记录数据符号信息的。

在许多种类的二维条码中,常用的码制有:Data Matrix, Maxi Code, Aztec, QR Code, Vericode, PDF417, Ultracode, Code 49, Code 16K等。
  1.堆叠式/行排式二维条码,如,Code 16K、Code 49、PDF417(如下图)等


 
    2.矩阵式二维码,最流行莫过于QR CODE
二维码的名称是相对与一维码来说的,比如以前的条形码就是一个“一维码”,
它的优点有:二维码存储的数据量更大;可以包含数字、字符,及中文文本等混合内容;有一定的容错性(在部分损坏以后可以正常读取);空间利用率高等。

QR(Quick-Response) code是被广泛使用的一种二维码,解码速度快。
它可以存储多用类型




 
如上图时一个qrcode的基本结构,其中:
位置探测图形、位置探测图形分隔符、定位图形:用于对二维码的定位,对每个QR码来说,位置都是固定存在的,只是大小规格会有所差异;
校正图形:规格确定,校正图形的数量和位置也就确定了;
格式信息:表示改二维码的纠错级别,分为L、M、Q、H;

版本信息:即二维码的规格,QR码符号共有40种规格的矩阵(一般为黑白色),从21x21(版本1),到177x177(版本40),每一版本符号比前一版本 每边增加4个模块。
数据和纠错码字:实际保存的二维码信息,和纠错码字(用于修正二维码损坏带来的错误)。




二维码的实现

编码思路:
    1. 数据分析:确定编码的字符类型,按相应的字符集转换成符号字符; 选择纠错等级,在规格一定的条件下,纠错等级越高其真实数据的容量越小。

    2. 数据编码:将数据字符转换为位流,每8位一个码字,整体构成一个数据的码字序列。其实知道这个数据码字序列就知道了二维码的数据内容。
          
 

 
 
            数据可以按照一种模式进行编码,以便进行更高效的解码,例如:对数据:01234567编码(版本1-H),
            1)分组:012 345 67
             2)转成二进制:012→0000001100
                                                   345→0101011001
                                                    67 →1000011
              3)转成序列:0000001100 0101011001 1000011
              4)字符数 转成二进制:8→0000001000
              5)加入模式指示符(上图数字)0001:0001 0000001000 0000001100 0101011001 1000011
           对于字母、中文、日文等只是分组的方式、模式等内容有所区别。基本方法是一致的

    3. 纠错编码:按需要将上面的码字序列分块,并根据纠错等级和分块的码字,产生纠错码字,并把纠错码字加入到数据码字序列后面,成为一个新的序列。
             

 
        在二维码规格和纠错等级确定的情况下,其实它所能容纳的码字总数和纠错码字数也就确定了,比如:版本10,纠错等级时H时,总共能容纳346个码字,其中224个纠错码字。
        就是说二维码区域中大约1/3的码字时冗余的。对于这224个纠错码字,它能够纠正112个替代错误(如黑白颠倒)或者224个据读错误(无法读到或者无法译码),
        这样纠错容量为:112/346=32.4%
       
    4. 构造最终数据信息:在规格确定的条件下,将上面产生的序列按次序放如分块中
        按规定把数据分块,然后对每一块进行计算,得出相应的纠错码字区块,把纠错码字区块 按顺序构成一个序列,添加到原先的数据码字序列后面。
        如:D1, D12, D23, D35, D2, D13, D24, D36, ... D11, D22, D33, D45, D34, D46, E1, E23,E45, E67, E2, E24, E46, E68,...

构造矩阵:将探测图形、分隔符、定位图形、校正图形和码字模块放入矩阵中。
         

 
        
         把上面的完整序列填充到相应规格的二维码矩阵的区域中


    6. 掩摸:将掩摸图形用于符号的编码区域,使得二维码图形中的深色和浅色(黑色和白色)区域能够比率最优的分布。
             一个算法,不研究了,有兴趣的同学可以继续。
    7. 格式和版本信息:生成格式和版本信息放入相应区域内。
        版本7-40都包含了版本信息,没有版本信息的全为0。二维码上两个位置包含了版本信息,它们是冗余的。
        版本信息共18位,6X3的矩阵,其中6位时数据为,如版本号8,数据位的信息时 001000,后面的12位是纠错位。


public final class KQRCordTools {

	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
	public static final String QRCODE_DEFAULT_CHARSET = "UTF-8";
	public static final int QRCODE_DEFAULT_HEIGHT = 150;
	public static final int QRCODE_DEFAULT_WIDTH = 150;

	private KQRCordTools() {
	}

	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 BufferedImage createQRCode(String contents, HashMap<EncodeHintType, ?> hints, BarcodeFormat format,
			int width, int height) throws WriterException {
		MultiFormatWriter formatWriter = new MultiFormatWriter();
		BitMatrix matrix = formatWriter.encode(contents, format, width, height, hints);
		return toBufferedImage(matrix);
	}

	public static BufferedImage createQRCode(String contents) throws WriterException {
		HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, QRCODE_DEFAULT_CHARSET);
		hints.put(EncodeHintType.MARGIN, 1);
		return createQRCode(contents, hints, BarcodeFormat.QR_CODE, QRCODE_DEFAULT_WIDTH, QRCODE_DEFAULT_HEIGHT);
	}

	public static BufferedImage addLogo4QRCode(BufferedImage qrCode, File logoFile)
			throws WriterException, IOException {
		BufferedImage logo = ImageIO.read(logoFile);
//		int deltaHeight = qrCode.getHeight() - logo.getHeight();
//		int deltawidth = qrCode.getWidth() - logo.getWidth();
//		//BufferedImage combined = new BufferedImage(qrCode.getHeight(), qrCode.getWidth(), BufferedImage.TYPE_INT_ARGB);
//		Graphics2D graph = (Graphics2D) qrCode.getGraphics();
//		graph.drawImage(qrCode, 0, 0, null);
//		graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1F));
//		graph.drawImage(logo, Math.round(deltawidth / 2), Math.round(deltaHeight / 2), null);
//		return qrCode;

		int matrixWidth = qrCode.getWidth();
		int matrixHeigh = qrCode.getHeight();
		Graphics2D graph = qrCode.createGraphics();
		graph.drawImage(logo, matrixWidth / 5 * 2, matrixHeigh / 5 * 2, matrixWidth / 5, matrixHeigh / 5, null);// 绘制
		BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
		graph.setStroke(stroke);// 设置笔画对象
		// 指定弧度的圆角矩形
		RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth / 5 * 2, matrixHeigh / 5 * 2,
				matrixWidth / 5, matrixHeigh / 5, 5, 5);
		graph.setColor(Color.white);
		graph.draw(round);// 绘制圆弧矩形

		// 设置logo 有一道灰色边框
		BasicStroke stroke2 = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
		graph.setStroke(stroke2);// 设置笔画对象
		RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth / 5 * 2 + 2, matrixHeigh / 5 * 2 + 2,
				matrixWidth / 5 - 4, matrixHeigh / 5 - 4, 5, 5);
		graph.setColor(new Color(128, 128, 128));
		graph.draw(round2);// 绘制圆弧矩形

		graph.dispose();
		qrCode.flush();
		return qrCode;
	}
}

public class QRCode {
	public static final String DEFAULT_IMAGE_FORMAT = "jpg";
	
	public static void create(String contents, String format, Path file, File logoFile) {
		try {
			BufferedImage qrCode = KQRCordTools.createQRCode(contents);
			if(logoFile != null) {
				qrCode = KQRCordTools.addLogo4QRCode(qrCode, logoFile);
			}
			if (!ImageIO.write(qrCode, format, file.toFile())) {
				throw new IOException("Could not write an image of format" + format);
			}
		}
		catch (WriterException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void create(String contents, Path file, File logoFile) {
		create(contents, DEFAULT_IMAGE_FORMAT, file, logoFile);
	}
	
	public static void create(String contents, String format, Path file) {
		create(contents, format, file, null);
	}

	public static void create(String contents, Path file) {
		create(contents, DEFAULT_IMAGE_FORMAT, file);
	}
	
	
	public static void analyze(String filePath) {
		try {
			MultiFormatReader formatReader = new MultiFormatReader();
			File file = new File(filePath);
			BufferedImage image = ImageIO.read(file);
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
			Map hints = new HashMap();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			Result result = formatReader.decode(binaryBitmap, hints);

			System.out.println("result = " + result.toString());
			System.out.println("resultFormat = " + result.getBarcodeFormat());
			System.out.println("resultText = " + result.getText());

		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public final class BufferedImageLuminanceSource extends LuminanceSource {

	private final BufferedImage image;
	private final int left;
	private final int top;

	public BufferedImageLuminanceSource(BufferedImage image) {
		this(image, 0, 0, image.getWidth(), image.getHeight());
	}

	public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
		super(width, height);

		int sourceWidth = image.getWidth();
		int sourceHeight = image.getHeight();
		if (left + width > sourceWidth || top + height > sourceHeight) {
			throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
		}

		for (int y = top; y < top + height; y++) {
			for (int x = left; x < left + width; x++) {
				if ((image.getRGB(x, y) & 0xFF000000) == 0) {
					image.setRGB(x, y, 0xFFFFFFFF); // = white
				}
			}
		}

		this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
		this.image.getGraphics().drawImage(image, 0, 0, null);
		this.left = left;
		this.top = top;
	}

	@Override
	public byte[] getRow(int y, byte[] row) {
		if (y < 0 || y >= getHeight()) {
			throw new IllegalArgumentException("Requested row is outside the image: " + y);
		}
		int width = getWidth();
		if (row == null || row.length < width) {
			row = new byte[width];
		}
		image.getRaster().getDataElements(left, top + y, width, 1, row);
		return row;
	}

	@Override
	public byte[] getMatrix() {
		int width = getWidth();
		int height = getHeight();
		int area = width * height;
		byte[] matrix = new byte[area];
		image.getRaster().getDataElements(left, top, width, height, matrix);
		return matrix;
	}

	@Override
	public boolean isCropSupported() {
		return true;
	}

	@Override
	public LuminanceSource crop(int left, int top, int width, int height) {
		return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
	}

	@Override
	public boolean isRotateSupported() {
		return true;
	}

	@Override
	public LuminanceSource rotateCounterClockwise() {

		int sourceWidth = image.getWidth();
		int sourceHeight = image.getHeight();

		AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);

		BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);

		Graphics2D g = rotatedImage.createGraphics();
		g.drawImage(image, transform, null);
		g.dispose();

		int width = getWidth();
		return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
	}

}

public class testQRCord {
	public static void main(String[] args) {
		String contents = "路漫漫兮其修远 ,吾将上下而求索.$$%$%$#$%&^&abasds*)(";
		String filePath = "C:\\Users\\lyh\\Pictures\\Saved Pictures\\1.jpg";
		String logoPath = "C:\\Users\\lyh\\Pictures\\Saved Pictures\\2.jpg";
		Path file = new File(filePath).toPath();
		QRCode.create(contents, file, new File(logoPath));
		QRCode.analyze(filePath);
	}
}


到此就完成了二维码的生成和解析


深入



参考鸣谢:

http://suflow.iteye.com/blog/1100678

http://www.cnblogs.com/wangyuyu/p/3410275.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值