二维码生成与解析

一、生成二维码
二、解析二维码
三、生成一维码
四、全部的代码
五、pom依赖

直接上代码:

一、生成二维码

public class demo {private static final String path1="D:\\code.jpg";private static void qr(String text,int width,int weight,String filepath) throws WriterException, IOException {//首先创建一个QRCodeWriter对象QRCodeWriter qrCodeWriter = new QRCodeWriter();//设置二维码信息:text{二维码信息},格式,宽度,高度BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE,width,weight);//设置生成的二维码要保存的地方Path path = FileSystems.getDefault().getPath(filepath);//设置转换后的格式和地址MatrixToImageWriter.writeToPath(bitMatrix,"JPG",path);}public static void main(String[] args) throws IOException, WriterException {//可以传网址、文本信息过去qr("www.baidu.com",350,350,path1);}
}

二、解析二维码

   /*** 从一个图片文件中解码出二维码中的内容。* * @param file* @return 解析后的内容。* @throws IOException* @throws ReaderException*/public static final String parseImage(File file) throws IOException, ReaderException {BufferedImage image = ImageIO.read(file);return parseImage(image);}/*** 从图片中解析出一维码或者二维码的内容。如果解析失败,则抛出NotFoundException。* @param image* @return* @throws NotFoundException*/public static final String parseImage(BufferedImage image) throws NotFoundException {LuminanceSource source = new BufferedImageLuminanceSource(image);Binarizer binarizer = new HybridBinarizer(source);BinaryBitmap bitmap = new BinaryBitmap(binarizer);Result result = READER.decode(bitmap);// 这里丢掉了Result中其他一些数据return result.getText();}

三、生成一维码

    /*** 将字符串编码成一维码(条形码)。* @param content* @return* @throws WriterException* @throws IOException*/public static BufferedImage createBarCode(String content) throws WriterException, IOException {MultiFormatWriter writer = new MultiFormatWriter();// 一维码的宽>高。这里我设置为 宽:高=2:1BitMatrix matrix = writer.encode(content, BarcodeFormat.EAN_13, BARCODE_WIDTH * 3, BARCODE_WIDTH);return toBufferedImage(matrix);}/*** 将一个BitMatrix对象转换成BufferedImage对象* * @param matrix* @return*/private 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;}

四、接着出一下全部的

package com.demo.ajax.demo;
/*** 二维码生成类(可生成二维码和条形码)*/
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import javax.servlet.http.HttpServletResponse;public class QRCodeUtil {// 这几项可以由其他调用的类设置,因此是public static的public static int BARCODE_WIDTH = 80;public static int QRCODE_WIDTH = 200;public static String FORMAT = "jpg";// 生成的图片格式public static int BLACK = 0x000000;// 编码的颜色public static int WHITE = 0xFFFFFF;// 空白的颜色// 二维码中间的图像配置。注意,由于二维码的容错率有限,因此中间遮挡的面积不要太大,否则可能解析不出来。private static int ICON_WIDTH = (int)(QRCODE_WIDTH / 6);private static int HALF_ICON_WIDTH = ICON_WIDTH / 2;private static int FRAME_WIDTH = 2;// Icon四周的边框宽度// 二维码读码器和写码器private static final MultiFormatWriter WRITER = new MultiFormatWriter();private static final MultiFormatReader READER = new MultiFormatReader();// 测试public static void main(String[] args) throws Exception {/*** 二维码测试。*/String iconPath = "D:\\code.jpg";String content = "http://www.baidu.com";File qrCode = new File("/home/lxf/qrcode/qrcode." + FORMAT);File qrCodeWithIcon = new File("/home/lxf/qrcode/qrcode_img." + FORMAT);// 生成二维码writeToFile(createQRCode(content), qrCode);// 生成带图标的二维码writeToFile(createQRCodeWithIcon(content, iconPath), qrCodeWithIcon);// 解析二维码System.out.println(parseImage(qrCode));// 解析带图标的二维码System.out.println(parseImage(qrCodeWithIcon));// 编码成字节数组byte[] data = createQRCodeToBytes(content);String result = parseQRFromBytes(data);System.out.println(result);/*** 一维码测试。*/String barCodeContent="6936983800013";File barCode = new File("C:\\BarCode." + FORMAT);// 生成一维码writeToFile(createBarCode(barCodeContent), barCode);// 解析一维码System.out.println(parseImage(barCode));}/*** 将String编码成二维码的图片后,使用字节数组表示,便于传输。* * @param content* @return* @throws WriterException* @throws IOException*/public static byte[] createQRCodeToBytes(String content) throws WriterException, IOException {BufferedImage image = createQRCode(content);ByteArrayOutputStream os = new ByteArrayOutputStream();ImageIO.write(image, FORMAT, os);return os.toByteArray();}/*** 把一个String编码成二维码的BufferedImage.* * @param content* @return* @throws WriterException*/public static final BufferedImage createQRCode(String content) throws WriterException {// 长和宽一样,所以只需要定义一个SIZE即可BitMatrix matrix = WRITER.encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_WIDTH);return toBufferedImage(matrix);}/*** 编码字符串为二维码,并在该二维码中央插入指定的图标。* @param content* @param iconPath* @return* @throws WriterException*/public static final BufferedImage createQRCodeWithIcon(String content, String iconPath) throws WriterException {BitMatrix matrix = WRITER.encode(content, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_WIDTH);// 读取Icon图像BufferedImage scaleImage = null;try {scaleImage = scaleImage(iconPath, ICON_WIDTH, ICON_WIDTH, true);} catch (IOException e) {e.printStackTrace();}int[][] iconPixels = new int[ICON_WIDTH][ICON_WIDTH];for (int i = 0; i < scaleImage.getWidth(); i++) {for (int j = 0; j < scaleImage.getHeight(); j++) {iconPixels[i][j] = scaleImage.getRGB(i, j);}}// 二维码的宽和高int halfW = matrix.getWidth() / 2;int halfH = matrix.getHeight() / 2;// 计算图标的边界:int minX = halfW - HALF_ICON_WIDTH;//左int maxX = halfW + HALF_ICON_WIDTH;//右int minY = halfH - HALF_ICON_WIDTH;//上int maxY = halfH + HALF_ICON_WIDTH;//下int[] pixels = new int[QRCODE_WIDTH * QRCODE_WIDTH];// 修改二维码的字节信息,替换掉一部分为图标的内容。for (int y = 0; y < matrix.getHeight(); y++) {for (int x = 0; x < matrix.getWidth(); x++) {// 如果点在图标的位置,用图标的内容替换掉二维码的内容if (x > minX && x < maxX && y > minY && y < maxY) {int indexX = x - halfW + HALF_ICON_WIDTH;int indexY = y - halfH + HALF_ICON_WIDTH;pixels[y * QRCODE_WIDTH + x] = iconPixels[indexX][indexY];}// 在图片四周形成边框else if ((x > minX - FRAME_WIDTH && x < minX + FRAME_WIDTH && y > minY - FRAME_WIDTH && y < maxY + FRAME_WIDTH)|| (x > maxX - FRAME_WIDTH && x < maxX + FRAME_WIDTH && y > minY - FRAME_WIDTH && y < maxY + FRAME_WIDTH)|| (x > minX - FRAME_WIDTH && x < maxX + FRAME_WIDTH && y > minY - FRAME_WIDTH && y < minY + FRAME_WIDTH)|| (x > minX - FRAME_WIDTH && x < maxX + FRAME_WIDTH && y > maxY - FRAME_WIDTH && y < maxY + FRAME_WIDTH)) {pixels[y * QRCODE_WIDTH + x] = WHITE;}else {// 这里是其他不属于图标的内容。即为二维码没有被图标遮盖的内容,用矩阵的值来显示颜色。pixels[y * QRCODE_WIDTH + x] = matrix.get(x, y) ? BLACK : WHITE;}}}// 用修改后的字节数组创建新的BufferedImage.BufferedImage image = new BufferedImage(QRCODE_WIDTH, QRCODE_WIDTH, BufferedImage.TYPE_INT_RGB);image.getRaster().setDataElements(0, 0, QRCODE_WIDTH, QRCODE_WIDTH, pixels);return image;}/*** 从一个二维码图片的字节信息解码出二维码中的内容。* * @param data* @return* @throws ReaderException* @throws IOException*/public static String parseQRFromBytes(byte[] data) throws ReaderException, IOException {ByteArrayInputStream is = new ByteArrayInputStream(data);BufferedImage image = ImageIO.read(is);return parseImage(image);}/*** 从一个图片文件中解码出二维码中的内容。* * @param file* @return 解析后的内容。* @throws IOException* @throws ReaderException*/public static final String parseImage(File file) throws IOException, ReaderException {BufferedImage image = ImageIO.read(file);return parseImage(image);}/*** 将字符串编码成一维码(条形码)。* @param content* @return* @throws WriterException* @throws IOException*/public static BufferedImage createBarCode(String content) throws WriterException, IOException {MultiFormatWriter writer = new MultiFormatWriter();// 一维码的宽>高。这里我设置为 宽:高=2:1BitMatrix matrix = writer.encode(content, BarcodeFormat.EAN_13, BARCODE_WIDTH * 3, BARCODE_WIDTH);return toBufferedImage(matrix);}/*** 从图片中解析出一维码或者二维码的内容。如果解析失败,则抛出NotFoundException。* @param image* @return* @throws NotFoundException*/public static final String parseImage(BufferedImage image) throws NotFoundException {LuminanceSource source = new BufferedImageLuminanceSource(image);Binarizer binarizer = new HybridBinarizer(source);BinaryBitmap bitmap = new BinaryBitmap(binarizer);Result result = READER.decode(bitmap);// 这里丢掉了Result中其他一些数据return result.getText();}/*** 将BufferedImage对象输出到指定的文件中。* * @param image* @param destFile* @throws IOException*/public static final void writeToFile(BufferedImage image, File destFile) throws IOException {ImageIO.write(image, FORMAT, destFile);}/*** 将BufferedImage对象直接response* @param image* @param response* @throws IOException*/public static final void showQrcode(BufferedImage image, HttpServletResponse response) throws IOException{ImageIO.write(image, FORMAT, response.getOutputStream());}/*** 将一个BitMatrix对象转换成BufferedImage对象* * @param matrix* @return*/private 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;}/*** 把传入的原始图像按高度和宽度进行缩放,生成符合要求的图标。* * @param srcImageFile 源文件地址* @param height 目标高度* @param width 目标宽度* @param hasFiller 比例不对时是否需要补白:true为补白; false为不补白;* @throws IOException*/private static BufferedImage scaleImage(String srcImageFile, int height, int width, boolean hasFiller) throws IOException {double ratio = 0.0; // 缩放比例File file = new File(srcImageFile);BufferedImage srcImage = ImageIO.read(file);Image destImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);// 计算比例if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {if (srcImage.getHeight() > srcImage.getWidth()) {ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();} else {ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();}AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);destImage = op.filter(srcImage, null);}if (hasFiller) {// 补白BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D graphic = image.createGraphics();graphic.setColor(Color.white);graphic.fillRect(0, 0, width, height);if (width == destImage.getWidth(null)) {graphic.drawImage(destImage, 0, (height - destImage.getHeight(null)) / 2, destImage.getWidth(null), destImage.getHeight(null), Color.white, null);} else {graphic.drawImage(destImage, (width - destImage.getWidth(null)) / 2, 0, destImage.getWidth(null), destImage.getHeight(null), Color.white, null);}graphic.dispose();destImage = image;}return (BufferedImage) destImage;}
}

五、pom依赖

<!-- https://mvnrepository.com/artifact/com.google.zxing/core --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.4.0</version></dependency><!-- https://mvnrepository.com/artifact/com.google.zxing/javase --><!-- https://mvnrepository.com/artifact/com.google.zxing/javase --><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.4.0</version></dependency>

条形码?二维码?生成、解析都在这里!相关推荐

  1. [开源]C#二维码生成解析工具,可添加自定义Logo

    原文:[开源]C#二维码生成解析工具,可添加自定义Logo 二维码又称 QR Code,QR 全称 Quick Response,是一个近几年来移动设备上超流行的一种编码方式,它比传统的 Bar Co ...

  2. 条形码/二维码生成探索

    条形码/二维码生成探索 所用依赖 <!--条形码生成依赖(轻量型,推荐使用这个)(生成条码的同时会把信息生成到条形码下)--><dependency><groupId&g ...

  3. python公司企业编码条形码二维码生成系统

    wx供重浩:创享日记 对话框发送:python编码 免费获取完整源码源文件+配置说明教程等 在PyCharm中运行<企业编码生成系统>即可进入如图1所示的系统主界面.在该界面中可以选择要使 ...

  4. JAVA基础--QR_Code二维码生成

    2019独角兽企业重金招聘Python工程师标准>>> 项目中我们经常会用到二维码,今天就来讲讲二维码的生成: 1, 二维码的概念:            二维条码/二维码(2-di ...

  5. springBoot二维码生成案例

    1.首先引入谷歌开源项目依赖: <!-- 二维码支持包 --> <dependency><groupId>com.google.zxing</groupId& ...

  6. 利用ZXing工具生成二维码以及解析二维码

    今天突然想到二维码是如何存储信息的.于是就开始各种搜索,最终自己也利用Google的ZXing工具完成了一个生成二维码和解析二维码的简单程序. 一. 二维码生成原理(即工作原理) 二维码官方叫版本Ve ...

  7. 个人用户永久免费,可自动升级版Excel插件,使用VSTO开发,Excel催化剂功能第12波-快速生成、读取、导出条形码二维码...

    根据指定的内容生成对应的条形码或二维码,在如今移动互联网时代,并不是一件什么新鲜事,随便百度一下,都能找到好多的软件或在线网站可以帮我们做到,但细想一下,如果很偶然地只是生成一个两这样的图形,百度一下 ...

  8. Zxing实现二维码生成和解析,可带logo

        在项目中使用zxing生成二维码提供项目支撑(ZXing是一个开源Java类库用于解析多种格式的条形码和二维码),其余SwetakeQRCode.BarCode4j等等工具可去了解. 简单介绍 ...

  9. html,vue, react,angular 前端实现二维码生成 ,二维码解析

    本文的背景 近期,由于项目开发的需求,需要前端实现图片二维码的解析. 由于需求的需要,这边调研了一下,发现很多人都有着类似的需求,网上给的解决方案也很多,但是感觉还是有些..... 又想到之前做过前端 ...

  10. Java利用Zxing生成二维码及解析二维码内容

    前言 Java 操作二维码的开源项目很多,如 SwetakeQRCode.BarCode4j.Zxing 等等 本篇文章是介绍利用Zxing来生成二维码图片在web网页上展示,同时解析二维码图片. Z ...

最新文章

  1. 我的LDAP使用手记(Fedora-ds) 备忘用
  2. 内地计算机学校,全球大学计算机实力排名:清北人工智能内地前2
  3. protobuf在go中的应用
  4. 增大mysql修改表空间_innodb系统表空间维护方法
  5. 13 SD配置-企业结构-分配-给销售办公室分配销售组
  6. 解决win2003不支持FLV播放的方法
  7. tesseract linux 训练
  8. 如何安装oracle数据库
  9. javaee版eclipse导包出现未找到类问题
  10. Flux、Mono、Reactor 实战(史上最全)
  11. Aliyun ECS 配置
  12. 让你越来越值钱的秘密:目标清单
  13. [iOS]ARC下循环引用的问题
  14. 新教育杂志新教育杂志社新教育编辑部2023年第6期目录
  15. 月模拟题3 201609-3 炉石传说
  16. Linux内核调试方法总结
  17. 纽约出租车旅途时间建模分析
  18. 关于flickr的数据集笔记
  19. 熟悉的时间,坚持就是胜利!
  20. [Perl]Perl匹配非空白字符[^\s]

热门文章

  1. 2022-2028年中国输送胶管行业市场全景调查及投资前景趋势报告
  2. 科大奥锐干涉法测微小量实验的数据_光学干涉观测精确丈量宇宙 | 赛先生天文...
  3. C++ OP相关注意事项
  4. MinkowskiPooling池化(上)
  5. 快速人体姿态估计:CVPR2019论文阅读
  6. 2021年大数据Flink(三十九):​​​​​​​Table与SQL ​​​​​​总结 Flink-SQL常用算子
  7. thinkphp5.1 中间件是什么有什么用
  8. DOM相关内容(课程来源:B站 后盾人)
  9. vsftpd的主配置文件是什么linux,linux下vsftpd配置文件选项详细说明
  10. python 保存内容到记事本里面