当前位置: 移动技术网 > IT编程>开发语言>Java > 用JAVA 设计生成二维码详细教程

用JAVA 设计生成二维码详细教程

2019年07月22日  | 移动技术网IT编程  | 我要评论

教你一步一步用 java 设计生成二维码

在物联网的时代,二维码是个很重要的东西了,现在无论什么东西都要搞个二维码标志,唯恐落伍,就差人没有用二维码识别了。也许有一天生分证或者户口本都会用二维码识别了。今天心血来潮,看见别人都为自己的博客添加了二维码,我也想搞一个测试一下.

主要用来实现两点:

1. 生成任意文字的二维码.

2. 在二维码的中间加入图像.

一、准备工作。

准备qr二维码3.0 版本的core包和一张jpg图片。

下载qr二维码包。

首先得下载 zxing.jar 包, 我这里用的是3.0 版本的core包

下载地址: 现在已经迁移到了github: https://github.com/zxing/zxing/wiki/getting-started-developing,

当然你也可以从maven仓库下载jar 包: http://central.maven.org/maven2/com/google/zxing/core/

二、程序设计

 1、启动eclipse,新建一个java项目,命好项目名(本例取名为qrcodesoft)。点下一步:

2、导入zxing.jar 包, 我这里用的是3.0 版本的core包:点“添加外部jar(x)…”。

3、新建两个类,分别是:

bufferedimageluminancesource.java

qrcodeutil.java

关键代码在于:bufferedimageluminancesource.java 和qrcodeutil.java , 其中测试的main 方法位于 qrcodeutil.java 中。

bufferedimageluminancesource.java程序代码:

package com.yihaomen.barcode;


import java.awt.graphics2d;
import java.awt.geom.affinetransform;
import java.awt.image.bufferedimage;

import com.google.zxing.luminancesource;

public 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;
	}

	
	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;
	}

	
	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;
	}

	
	public boolean iscropsupported() {
		return true;
	}

	
	public luminancesource crop(int left, int top, int width, int height) {
		return new bufferedimageluminancesource(image, this.left + left,
				this.top + top, width, height);
	}

	
	public boolean isrotatesupported() {
		return true;
	}

	
	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);
	}
}

qrcodeutil.java的程序代码:

package com.yihaomen.barcode;



import java.awt.basicstroke;
import java.awt.graphics;
import java.awt.graphics2d;
import java.awt.image;
import java.awt.shape;
import java.awt.geom.roundrectangle2d;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.outputstream;
import java.util.hashtable;
import java.util.random;

import javax.imageio.imageio;

import com.google.zxing.barcodeformat;
import com.google.zxing.binarybitmap;
import com.google.zxing.decodehinttype;
import com.google.zxing.encodehinttype;
import com.google.zxing.multiformatreader;
import com.google.zxing.multiformatwriter;
import com.google.zxing.result;
import com.google.zxing.common.bitmatrix;
import com.google.zxing.common.hybridbinarizer;
import com.google.zxing.qrcode.decoder.errorcorrectionlevel;

/**
 * 二维码工具类
 * 
 */
public class qrcodeutil {

	private static final string charset = "utf-8";
	private static final string format_name = "jpg";
	// 二维码尺寸
	private static final int qrcode_size = 300;
	// logo宽度
	private static final int width = 60;
	// logo高度
	private static final int height = 60;

	private static bufferedimage createimage(string content, string imgpath,
			boolean needcompress) throws exception {
		hashtable<encodehinttype, object> hints = new hashtable<encodehinttype, object>();
		hints.put(encodehinttype.error_correction, errorcorrectionlevel.h);
		hints.put(encodehinttype.character_set, charset);
		hints.put(encodehinttype.margin, 1);
		bitmatrix bitmatrix = new multiformatwriter().encode(content,
				barcodeformat.qr_code, qrcode_size, qrcode_size, hints);
		int width = bitmatrix.getwidth();
		int height = bitmatrix.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, bitmatrix.get(x, y) ? 0xff000000
						: 0xffffffff);
			}
		}
		if (imgpath == null || "".equals(imgpath)) {
			return image;
		}
		// 插入图片
		qrcodeutil.insertimage(image, imgpath, needcompress);
		return image;
	}

	/**
	 * 插入logo
	 * 
	 * @param source
	 *   二维码图片
	 * @param imgpath
	 *   logo图片地址
	 * @param needcompress
	 *   是否压缩
	 * @throws exception
	 */
	private static void insertimage(bufferedimage source, string imgpath,
			boolean needcompress) throws exception {
		file file = new file(imgpath);
		if (!file.exists()) {
			system.err.println(""+imgpath+" 该文件不存在!");
			return;
		}
		image src = imageio.read(new file(imgpath));
		int width = src.getwidth(null);
		int height = src.getheight(null);
		if (needcompress) { // 压缩logo
			if (width > width) {
				width = width;
			}
			if (height > height) {
				height = height;
			}
			image image = src.getscaledinstance(width, height,
					image.scale_smooth);
			bufferedimage tag = new bufferedimage(width, height,
					bufferedimage.type_int_rgb);
			graphics g = tag.getgraphics();
			g.drawimage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			src = image;
		}
		// 插入logo
		graphics2d graph = source.creategraphics();
		int x = (qrcode_size - width) / 2;
		int y = (qrcode_size - height) / 2;
		graph.drawimage(src, x, y, width, height, null);
		shape shape = new roundrectangle2d.float(x, y, width, width, 6, 6);
		graph.setstroke(new basicstroke(3f));
		graph.draw(shape);
		graph.dispose();
	}

	/**
	 * 生成二维码(内嵌logo)
	 * 
	 * @param content
	 *   内容
	 * @param imgpath
	 *   logo地址
	 * @param destpath
	 *   存放目录
	 * @param needcompress
	 *   是否压缩logo
	 * @throws exception
	 */
	public static void encode(string content, string imgpath, string destpath,
			boolean needcompress) throws exception {
		bufferedimage image = qrcodeutil.createimage(content, imgpath,
				needcompress);
		mkdirs(destpath);
		string file = new random().nextint(99999999)+".jpg";
		imageio.write(image, format_name, new file(destpath+"/"+file));
	}

	/**
	 * 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
	 * @author lanyuan
	 * email: mmm333zzz520@163.com
	 * @date 2013-12-11 上午10:16:36
	 * @param destpath 存放目录
	 */
	public static void mkdirs(string destpath) {
		file file =new file(destpath); 
		//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
		if (!file.exists() && !file.isdirectory()) {
			file.mkdirs();
		}
	}

	/**
	 * 生成二维码(内嵌logo)
	 * 
	 * @param content
	 *   内容
	 * @param imgpath
	 *   logo地址
	 * @param destpath
	 *   存储地址
	 * @throws exception
	 */
	public static void encode(string content, string imgpath, string destpath)
			throws exception {
		qrcodeutil.encode(content, imgpath, destpath, false);
	}

	/**
	 * 生成二维码
	 * 
	 * @param content
	 *   内容
	 * @param destpath
	 *   存储地址
	 * @param needcompress
	 *   是否压缩logo
	 * @throws exception
	 */
	public static void encode(string content, string destpath,
			boolean needcompress) throws exception {
		qrcodeutil.encode(content, null, destpath, needcompress);
	}

	/**
	 * 生成二维码
	 * 
	 * @param content
	 *   内容
	 * @param destpath
	 *   存储地址
	 * @throws exception
	 */
	public static void encode(string content, string destpath) throws exception {
		qrcodeutil.encode(content, null, destpath, false);
	}

	/**
	 * 生成二维码(内嵌logo)
	 * 
	 * @param content
	 *   内容
	 * @param imgpath
	 *   logo地址
	 * @param output
	 *   输出流
	 * @param needcompress
	 *   是否压缩logo
	 * @throws exception
	 */
	public static void encode(string content, string imgpath,
			outputstream output, boolean needcompress) throws exception {
		bufferedimage image = qrcodeutil.createimage(content, imgpath,
				needcompress);
		imageio.write(image, format_name, output);
	}

	/**
	 * 生成二维码
	 * 
	 * @param content
	 *   内容
	 * @param output
	 *   输出流
	 * @throws exception
	 */
	public static void encode(string content, outputstream output)
			throws exception {
		qrcodeutil.encode(content, null, output, false);
	}

	/**
	 * 解析二维码
	 * 
	 * @param file
	 *   二维码图片
	 * @return
	 * @throws exception
	 */
	public static string decode(file file) throws exception {
		bufferedimage image;
		image = imageio.read(file);
		if (image == null) {
			return null;
		}
		bufferedimageluminancesource source = new bufferedimageluminancesource(
				image);
		binarybitmap bitmap = new binarybitmap(new hybridbinarizer(source));
		result result;
		hashtable<decodehinttype, object> hints = new hashtable<decodehinttype, object>();
		hints.put(decodehinttype.character_set, charset);
		result = new multiformatreader().decode(bitmap, hints);
		string resultstr = result.gettext();
		return resultstr;
	}

	/**
	 * 解析二维码
	 * 
	 * @param path
	 *   二维码图片地址
	 * @return
	 * @throws exception
	 */
	public static string decode(string path) throws exception {
		return qrcodeutil.decode(new file(path));
	}

	public static void main(string[] args) throws exception {
		string text = "http://www.yihaomen.com";
		qrcodeutil.encode(text, "c:/me.jpg", "c:/barcode", true);
	}
}

生成不带logo 的二维码

程序代码如下:

public static void main(string[] args) throws exception {
  string text = "http://www.dans88.com.cn";
  qrcodeutil.encode(text,"","d:/myworkdoc",true);
}

运行这个测试方法,生成的二维码不带 logo , 样式如下:

有兴趣可以用手机扫描一下

生成带logo 的二维码

logo 可以用自己的头像,或者自己喜欢的一个图片都可以 , 采用如下代码,程序代码如下:

public static void main(string[] args) throws exception {
  string text = "http://www.dans88.com.cn";
  qrcodeutil.encode(text, "d:/myworkdoc/my180.jpg", "d:/myworkdoc", true);
 } 

唯一的区别是,在前面的基础上指定了logo 的地址,这里测试都用了c盘的图片文件

用手机扫描,能出现要出现的文字,点击就进入自己的网站。

以上就是用java 设计生成二维码,有兴趣的朋友可以参考下,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网