自从微信扫描出世,二维码扫描逐渐已经成为一种主流的信息传递和交换方式。下面就介绍一下我学习到的这种二维码生成方式。预计再过不久身份证户口本等都会使用二维码识别了,今天就做一个实验案例;

二维码主要实现这两点:

  1.生成任意的二维码。

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

 一、准备工作。

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

下载QR二维码包。

当然你也可以从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

package com.code.liu;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);}
}

 
package com.code.liu;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) { // 压缩LOGOif (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;}// 插入LOGOGraphics2D 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.cnblogs.com/qianxiaoruofeng/";QRCodeUtil.encode(text, "c:/Users/Administrator/Desktop/liupeng/1.png", "c:/Users/Administrator/Desktop/liupeng/barcode", true);}
}

生成不带logo 的二维码

程序代码

public static void main(String[] args) throws Exception {
        String text = "http://www.cnblogs.com/qianxiaoruofeng/";

QRCodeUtil.encode(text,"", "c:/Users/Administrator/Desktop/liupeng/barcode",true);

}

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

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

生成带logo 的二维码 
logo 可以用自己的头像,或者自己喜欢的一个图片都可以 , 采用如下代码

程序代码

public static void main(String[] args) throws Exception {
        String text = "http://www.cnblogs.com/qianxiaoruofeng/";

      QRCodeUtil.encode(text, "c:/Users/Administrator/Desktop/liupeng/1.png", "c:/Users/Administrator/Desktop/liupeng/barcode", true);

    }

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

手机扫描二维码进入浅笑若风的博客。

转载于:https://www.cnblogs.com/qianxiaoruofeng/p/8391460.html

java二维码生成技术相关推荐

  1. java二维码生成-谷歌(Google.zxing)开源二维码生成学习及实例

    java二维码生成-谷歌(Google.zxing)开源二维码生成的实例及介绍  这里我们使用比特矩阵(位矩阵)的QR码编码在缓冲图片上画出二维码 实例有以下一个传入参数 OutputStream o ...

  2. java二维码生成 使用SSM框架 搭建属于自己的APP二维码合成、解析、下载

    java二维码生成 使用SSM框架 搭建属于自己的APP二维码合成.解析.下载 自己用java搭建一个属于自己APP二维码合成网站.我的思路是这样的: 1.用户在前台表单提交APP的IOS和Andro ...

  3. 【笔记11】uniapp点击复制;mysql数据库存储emoji表情;Java 二维码生成;uniapp引入自定义图标

    目录 前言 一.uniapp 实现点击复制某段文本 二.MySQL 数据库存储 emoji 表情 三.Layui 的富文本编辑器 四.谷歌 Java 二维码生成 (1) 引入 MAVEN 依赖 五.微 ...

  4. java 二维码生成和解析

    2019独角兽企业重金招聘Python工程师标准>>> <!-- 二维码 --><dependency><groupId>com.google.z ...

  5. java二维码生成并可以转换

    二维码很常见,简单的二维码生成 pom中导入两个包 <!--二维码--><dependency><groupId>com.google.zxing</grou ...

  6. Java—二维码生成与识别(一)

    一.二维码生成 思路:将字符串中的每个字符转为二进制码字符串,保存在二进制码字符串数组中.对二进制码字符串数组中的每个二进制码字符串进行字符遍历,若是'0',则设置画笔颜色为白色,若是'1',则设置画 ...

  7. java 二维码生成及其标签打印

    本文主要内容 二维码生成 二维码标签预览及打印 二维码生成 笔者此次的二维码是通过调用第三方接口生成的,具体流程如下: 根据规范要求调用第三方接口,返回二维码下载地址及二维码图片的属性值(图片大小等) ...

  8. java 二维码生成和加密base64压码

    因为项目中要实现扫描二维码并实现登录,但本人开发的模块是服务器,跟前台传输用到的主要是json对象.所以不能直接传输图片,必须把图片加密成base64压码的形式. 首先介绍二维码生成的代码,二维码生成 ...

  9. java二维码生成导出成压缩包

    效果: 首先引入zxing依赖: <lombok.version>1.18.8</lombok.version> <zxing.version>3.3.3</ ...

最新文章

  1. 利用XGboost简单粗暴zillow竞赛25%
  2. 通过Iframe在A网站页面内嵌入空白页面的方式,跨域获取B网站的数据返回给A网站!...
  3. HDU2015校赛 The Country List
  4. python实现气象数据分析统计服_Python数据分析实战:降雨量统计分析报告分析
  5. 深度学习之keras (一) 初探
  6. MQTT和Java入门
  7. it男java_java-学习8
  8. c语言将整数的各个位数的数字分别提取_C语言学习:单位转换问题的一些思路...
  9. c语言dda算法完整实现,计算机图形学DDA算法.doc
  10. HY-SRF05 五针超声波测距模块 在stm32f4上实现 附代码 个人经验
  11. error: File: XX 520.13 MB, exceeds 100.00 MB以上大文件导致push失败解决方法
  12. 【多线程】送你1万朵玫瑰花
  13. 考勤 日历 ajax,vue实现钉钉的考勤日历
  14. mysql数据备份恢复
  15. 【构成L4笔记:拆解分组再构筑】
  16. 关于机器视觉机械手与相机标定走位点位的计算模块
  17. 【已解决】谷歌浏览器使用上传插件Uploadify的上传按钮不显示
  18. 【课程作业】实现高斯低通滤波器并与理想低通滤波器进行效果比较
  19. 差压变送器需要注意的问题
  20. 中国EDONG网(中国排名第16的IDC)的技术力量和他的24小时客服。

热门文章

  1. java截取字符串拼接_java截取字符串并拼接
  2. 无线抄表免费透传云服务器,两个WIFI模块USR-WIFI232-B2连接有人云实现远程一对一透传...
  3. Java 启动和停止界面_IntelliJ IDEA 2019.3 发布,启动更快,性能更好(新特性解读)...
  4. 【maven】使用(阿里云 aliyun)镜像仓库
  5. 微型计算机接口期末,最新大学微机原理与接口技术期末试题及答案
  6. list.action.php,教你利用 PHP 实现高性能微服务部署
  7. python mount回调函数_让Python脚本暂停执行的几种方法(小结)
  8. java neo4j_java连接neo4j
  9. linux哪个命令可以切换工作目录?如何显示当前所在的目录,Linux cd命令:切换目录...
  10. python selenium 框架说明_基于python+selenium的框架思路(二)