Java实现简单二维码制作

       二维码概述

       我们生活中使用到二维码的场景:

       

       二维码概念

       二维条码/二维码(2-dimensional bar code)是用某种特定的几何图形按一定规律在平面(二维方向上)分布的黑白

相间的图形记录数据符号信息的图形。

      在代码编制上巧妙地利用构成计算机内部逻辑基础的"0"、"1"比特流的概念,使用若干个与二进制相对应的几何

形体来表示文字数值信息,通过图象输入设备或光电扫描设备自动识读以实现信息自动处理:它具有条码技术的一些

共性:每种码制有其特定的字符集;每个字符占有一定的宽度;具有一定的校验功能等。同时还具有对不同行的信息

自动识别功能、及处理图形旋转变化点。

      二维码发展历史图示:

      

      一维条码

      

      1)一维条码是由一组粗细不同、黑白(或彩色)相同的条、空机器相应的字符(数字字母)组成的标记,即传统条码。

      二维条码

      

      2)二维条码是用某种特定的几何何图形按一定规律在平面(二维方向上)分布的条、空相间的图形来记录数据符号信

息。

       二维码分类

       二维条码也有许多不同的码制,就码制的编码原理而言,通常分为三种类型:

       1)线性堆叠式二维码

       

       编码原理:建立在一维条码基础之上,按需要堆积成两行或多行。

       2)矩阵式二维码

       最为常用的类型。

       

       编码原理:在一个矩形空间通过黑、白像素在矩阵中的不同分布进行编码。

在矩阵相应元素位置上,用点(方点、圆点或者其他形状)的出现表示二进制"1",点的不出现表示二进制的"0"

       3)邮政码

       编码原理:邮政码通过不同长度的条进行编码,主要用于邮件编码

       如:POSTNET、BPO 4-STATE

       二维码优缺点

       优点:

       1)高密度编码,信息容量大

       2)编码范围广

       3)容错能力强

       4)译码可靠性高

       5)可引入加密措施

       6)成本低,易制作,持久耐用

       缺点:

       1)二维码技术成为手机病毒、钓鱼网站传播的新渠道

       2)信息泄露

       OR Code简介

       目前流行的三大国际标准:

       1)PDF417:不支持中文

       2)DM:专利未公开,需支付专利费用

       3)QR Code:专利公开,支持中文

       QR Code比其他二维码相比,具有识读速度快,数据密度大,占用空间小的优势。QR Code是由日本Denso公

司于1994年研制的一种矩阵二维码符号码,全称是Quick Response Code。

        制作QR Code二维码的三种方式:

        借助jar包zxing

        生成二维码的CreateQRCode.java源文件

package com.zxing;


import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;


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.decoder.ErrorCorrectionLevel;


/**
 * 生成二维码
 * @author Administrator
 * @date 2016年7月29日
 */
public class CreateQRCode {


	public static void main(String[] args) {
		
		int width = 300;//二维码图片的宽度
		int height = 300;//二维码图片的高度
		String format = "png";//二维码格式
		String content = "http://www.imooc.com";//二维码内容
		
		//定义二维码内容参数
		HashMap hints = new HashMap();
		//设置字符集编码格式
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		//设置容错等级,在这里我们使用M级别
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		//设置边框距
		hints.put(EncodeHintType.MARGIN, 2);
		
		//生成二维码
		try {
			//指定二维码内容
			BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
			//指定生成图片的保存路径
			Path file = new File("D:/code/imooc.png").toPath();
			//生成二维码
			MatrixToImageWriter.writeToPath(bitMatrix, format, file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}

        运行结果:

        

        解析二维码的ReadQRCode.java源文件:

package com.zxing;


import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;


import javax.imageio.ImageIO;


import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;


public class ReadQRCode {


	public static void main(String[] args) {
		try {
			MultiFormatReader formatReader = new MultiFormatReader();
			File file = new File("D:/code/t.png");
			BufferedImage image = ImageIO.read(file);
			BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
			
			//定义二维码的参数
			HashMap hints = new HashMap();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			Result result = formatReader.decode(binaryBitmap,hints);
			
			System.out.println("解析结果:" + result.toString());
			System.out.println("二维码格式类型:" + result.getBarcodeFormat());
			System.out.println("二维码文本内容:" + result.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}


}

        运行结果:

        

        (2)借助jar包qrcodejar

        生成二维码的CreateQRCode.java源文件:

package com.qrcode;


import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;


import javax.imageio.ImageIO;


import com.sun.prism.Image;
import com.swetake.util.Qrcode;


public class CreateQRCode {


	public static void main(String[] args) throws Exception {
		Qrcode x = new Qrcode();
		//N代表数字,A代表a-z,B代表其他字符
		x.setQrcodeEncodeMode('B');
		//设置纠错等级
		x.setQrcodeErrorCorrect('M');
		//设置版本号(1-40)
		x.setQrcodeVersion(7);
		
		String qrDate = "http://www.baidu.com";
		int width = 67+12*(7-1);
		int height = 67+12*(7-1);
		int pixoff = 2;//偏移量
		
		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D gs = bufferedImage.createGraphics();
		gs.setBackground(Color.WHITE);
		gs.setColor(Color.BLACK);
		gs.clearRect(0, 0, width, height);
		
		byte[] d = qrDate.getBytes("UTF-8"); 
		if(d.length>0&&d.length<120){
			boolean[][] s = x.calQrcode(d);
			for(int i=0;i<s.length;i++){
			    for(int j=0;j<s.length;j++){
					if(s[j][i]){
						gs.fillRect(j*3+pixoff, i*3+pixoff, 3, 3);
					}
				}
			}
		}
		
		gs.dispose();
		bufferedImage.flush();
		ImageIO.write(bufferedImage, "png", new File("D:/code/baidu.png"));
	}


}

        辅助类MyQRCodeImage.java源文件:

package com.qrcode;


import java.awt.image.BufferedImage;


import jp.sourceforge.qrcode.data.QRCodeImage;


public class MyQRCodeImage implements QRCodeImage {
	BufferedImage bufferedImagees;


	public MyQRCodeImage(BufferedImage bufferedImage){
		this.bufferedImagees = bufferedImage;
	}
	
	@Override
	public int getHeight() {
		return bufferedImagees.getHeight();
	}


	@Override
	public int getPixel(int arg0, int arg1) {
		return bufferedImagees.getRGB(arg0, arg1);
	}


	@Override
	public int getWidth() {
		return bufferedImagees.getWidth();
	}


}

        运行结果:

        

        解析二维码的ReadQRCode.java源文件:

package com.qrcode;


import java.awt.image.BufferedImage;
import java.io.File;


import javax.imageio.ImageIO;


import jp.sourceforge.qrcode.QRCodeDecoder;


public class ReadQRCode {
	public static void main(String[] args) throws Exception {
		
		File file = new File("D:/code/baidu.png");
		
		BufferedImage bufferedImage = ImageIO.read(file);
		
		QRCodeDecoder codeDecoder = new QRCodeDecoder();
		codeDecoder.decode(new MyQRCodeImage(bufferedImage));
		
		String result = new String(codeDecoder.decode(new  MyQRCodeImage(bufferedImage)), "UTF-8");
		System.out.println("解析二维码的内容:" + result);
		
	}


}

        运行结果:

        

        借助jquert.qrcode.js

        index.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>二维码制作</title>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.qrcode.min.js"></script>
</head>
<body>
       <h1>生成二维码如下:</h1>
       <hr/>
       <div id="qrcode"></div>
       
       <script type="text/javascript" >
            jQuery('#qrcode').qrcode("http://www.qq.com");
       </script>
</body>
</html>

        运行结果:

        

        使用上面解析的结果是:

        



  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
你可以使用第三方库zxing来实现生成二维码的功能。以下是一个简单Java代码示例: ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class QRCodeGenerator { public static void main(String[] args) { String text = "https://www.example.com"; // 要生成二维码的文本内容 int width = 300; // 二维码图片宽度 int height = 300; // 二维码图片高度 String format = "png"; // 二维码图片格式 try { // 设置二维码参数 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 将二维码数据写入BufferedImage对象中 for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int rgb = bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF; bufferedImage.setRGB(x, y, rgb); } } // 将BufferedImage对象保存为图片文件 File outputFile = new File("qrcode." + format); ImageIO.write(bufferedImage, format, outputFile); System.out.println("二维码生成成功!"); } catch (WriterException | IOException e) { e.printStackTrace(); } } } ``` 以上代码使用zxing库生成一个指定文本内容的二维码,并将其保存为图片文件。你可以根据需要修改文本内容、图片尺寸和格式等参数。记得在运行代码前,确保已经导入zxing库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值