点击上方“方志朋”,选择“设为星标”

回复”666“获取新整理的面试文章


作者:红颜祸水nvn

来源:http://suo.im/5R6ewH

步骤1

第一步首先创建一个普通的 Maven 项目,然后要实现二维码功能,我们肯定要使用别人提供好的 Jar 包,这里我用的是 google 提供的 jar,pom.xml 文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.javaboy</groupId><artifactId>QRCode</artifactId><version>1.0-SNAPSHOT</version><dependencies><!-- 添加 google 提供的二维码依赖 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.0</version></dependency></dependencies></project>

步骤2

然后使用 google 提供的工具类,在项目根目录下创建一个 util 包,将所需要的工具类放进去。

工具类1 (BufferedImageLuminanceSource)

不废话,直接上代码

/*** @author bai <br/>* @date 2020/7/1 9:27<br/>*/
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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic boolean isCropSupported() {return true;}@Overridepublic LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);}@Overridepublic boolean isRotateSupported() {return true;}@Overridepublic 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);}}

工具类2 (QRCodeUtil)

这里面可以修改一些参数,例如二维码的尺寸,宽高等等。

/*** @author bai <br/>* @date 2020/7/1 9:29<br/>*/
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 hints = new Hashtable();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;}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();}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));ImageIO.write(image, FORMAT_NAME, new File(destPath));}public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);return image;}public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}public static void encode(String content, String imgPath, String destPath) throws Exception {QRCodeUtil.encode(content, imgPath, destPath, false);}// 被注释的方法/** public static void encode(String content, String destPath, boolean* needCompress) throws Exception { QRCodeUtil.encode(content, null, destPath,* needCompress); }*/public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}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);}public static void encode(String content, OutputStream output) throws Exception {QRCodeUtil.encode(content, null, output, false);}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 hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}}

启动类

这一步就是调用方法,一般大家使用这种功能都是为了实现业务,例如常见的扫描二维码跳转链接(页面),扫描二维码出现文字等等。有些二维码中间还带有 Logo 这种图片,将需要嵌入二维码的图片路径准备好就没有问题。

/*** @author bai <br/>* @date 2020/7/1 9:31<br/>*/
public class QRCodeApplication {public static void main(String[] args) throws Exception {// 存放在二维码中的内容// 二维码中的内容可以是文字,可以是链接等String text = "http://www.baidu.com";// 嵌入二维码的图片路径//String imgPath = "C:\\Users\\Administrator\\Pictures\\img\\dog.jpg";// 生成的二维码的路径及名称String destPath = "C:\\Users\\bai\\Pictures\\img\\code" + System.currentTimeMillis() + ".jpg";//生成二维码QRCodeUtil.encode(text, null, destPath, true);// 解析二维码String str = QRCodeUtil.decode(destPath);// 打印出解析出的内容System.out.println(str);}
}

效果截图

源码奉上

码云:https://gitee.com/jian_bo_bai/QRCode


热门内容:因用了Insert into select语句,美女同事被开除了!
我们已经不用AOP做操作日志了!Spring Boot+JWT+Shiro+MyBatisPlus 实现 RESTful 快速开发后端脚手架
MyBatis动态SQL(认真看看, 以后写SQL就爽多了)最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

明天见(。・ω・。)ノ♡

Java 如何实现二维码?相关推荐

  1. Java 快速开发二维码生成服务

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 来源 | 公众号「码农小胖哥」 1. 前言 不知道从什么 ...

  2. 在java中生成二维码,并直接输出到jsp页面

    在java中生成的二维码不存到磁盘里要直接输出到页面上,这就需要把生成的二维码直接以流的形式输出到页面上,我用的是myeclipse 和 tomcat 它的原理是:在加载页面时,根据img的src(c ...

  3. Java中识别二维码并且提高二维码的识别率

    我们在Java开发的时候,发现对二维码的识别是不足的.所以我们需要提高识别率. 第一步.识别图片二维码.准备相应的jar包.我们在gradle+idea中开发. compile group: 'com ...

  4. java生成圆形二维码logo

    自定义生成二维码,可以根据自己的喜欢在二维码中添加图片.有些代码是参考网上某位大神的,如有相同之处,请给我留言,我加上您的名字或者不让参考发表,则可删除. jar提取地址: 链接: https://p ...

  5. java实现生成二维码及扫码登录

    java实现生成二维码及扫码登录 1. 场景描述 2. 实现思路 3. 代码实现过程 3.1 pom.xml 3.2 二维码工具类 3.3 生成二维码并下载为图片 3.4 扫码登录 1. 场景描述   ...

  6. 用java实现表白二维码(附源码)

    用java实现表白二维码(附源码) 以下源码可以实现生成一个表白二维码,扫描二维码就能看到二维码里蕴藏的信息. import com.google.zxing.BarcodeFormat;import ...

  7. Java自定义生成二维码(兼容你所有的需求)

    1.概述 作为Java开发人员,说到生成二维码就会想到zxing开源二维码图像处理库,不可否认的是zxing确实很强大,但是实际需求中会遇到各种各样的需求是zxing满足不了的,于是就有了想法自己扩展 ...

  8. Java解析生成二维码-log

    Java解析生成二维码 1.pom.xml依赖 <!-- 引入二维码相关的依赖--><dependency><groupId>com.google.zxing< ...

  9. java生成文字二维码、url二维码

    java生成文字二维码.url二维码 pom: 1)生成文字二维码 java工具类: 2)url地址生成二维码 java工具类: pom: <dependency><groupId& ...

  10. java代码实现二维码图片的生成和解析

    2015年什么最火,二维码,2016年随处可见的是什么,二维码.二维码的历史我们就不探究了,今天分享的是利用Java代码实现二维码的生成和解析.Java代码生成和解析二维码涉及到的东西比较多,还需要引 ...

最新文章

  1. 「 每日一练,快乐水题 」599. 两个列表的最小索引总和
  2. 常见Eclipse SVN插件报错解决方法
  3. 双linux共用swap,在Linux和FreeBSD系统上共享swap空间
  4. java实现log4j_log4j在java中实现
  5. 用计算机对话的小品,爆笑小品剧本台词《作弊记》
  6. 一个简单地C语言程序展示RSA加密原理
  7. 百变方块java代码_多牛百变方块
  8. 使用 Spark ML Pipeline 进行机器学习
  9. python语言是非开源语言_python是非开源语言吗
  10. 苹果Mac Win10式任务栏工具:uBar
  11. BZOJ 1230: [Usaco2008 Nov]lites 开关灯( 线段树 )
  12. c语言爱心代码简单,利用c语言实现简单心形的代码分享
  13. 江苏省苏州市谷歌高清卫星地图下载
  14. 软件体系结构期末复习(快速入门考试)
  15. 让世界不再有“此生未完成”,臻和科技为患者带来守护之力
  16. 【TensorFlow】tf.expand_dims()函数
  17. 成功解决win7安装python过程,Setup failed,需要安装Windows 7 Service Pack 1
  18. PCIe 复位:Clod reset、warm reset、Hot reset、Function level reset
  19. 千图网爬图片(BeautifulSoup)
  20. NAS自回血方案介绍

热门文章

  1. vue 前端框架 (三)
  2. 1008: [HNOI2008]越狱(计数问题)
  3. -lt -gt -ge -le -eq的意义
  4. sqljdbc.jar 和 sqljdbc4.jar
  5. 浅浅认识之VBS脚本访问接口与COMODO拦截COM接口
  6. ASP.NET 2.0站点登录、导航与权限管理
  7. 学编程必看:逻辑思维测试
  8. Task03:青少年软件编程(Scratch)等级考试模拟卷(一级)
  9. 【第22周复盘】可以查成绩了!
  10. Modeling System Behavior with Use Case(3)