Java生成读取条形码和二维码的简单示例


Posted in Java/Android onJuly 09, 2021

条形码

将宽度不等的多个黑条和白条,按照一定的编码规则排序,用以表达一组信息的图像标识符

通常代表一串数字 / 字母,每一位有特殊含义

一般数据容量30个数字 / 字母

二维码

用某种特定几何图形按一定规律在平面(二维方向上)分布的黑白相间的图形记录数据符号信息

比一维条形码能存储更多信息,表示更多数据类型

能够存储数字 / 字母 / 汉字 / 图片等信息

可存储几百到几十KB字符

Zxing

Zxing主要是Google出品的,用于识别一维码和二维码的第三方库

主要类:

  • BitMatrix位图矩阵
  • MultiFormatWriter位图编写器
  • MatrixToImageWriter写入图片

Maven导入Zxing

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

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.0.0</version>
        </dependency>
</dependencies>

生成一维码java

public static void main(String[] args) {
    generateCode(new File("1dcode.png"), "1390351289", 500, 250);
}
/**
 * @param file    生成的文件名称
 * @param code    一维码存储的数据信息
 * @param width   生成图片的宽度
 * @param height  生成图片的高度
 * @return void
 * */
public static void generateCode(File file, String code, int width, int height){
    // 定义位图矩阵BitMatrix
    BitMatrix matrix = null;
    try {
        // 使用code_128格式进行编码生成100*25的条形码
        MultiFormatWriter writer = new MultiFormatWriter();

        matrix = writer.encode(code, BarcodeFormat.CODE_128, width, height, null);
    } catch (WriterException e) {
        e.printStackTrace();
    }

    // 将位图矩阵BitMatrix保存为图片
    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png", outputStream);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

注意:一维码只能存储数字和字母,其他数据会报Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.0.0:exec (default-cli) on project MavenDemo: Command execution failed.错误java

读取一维码

public static void main(String[] args) {
    readCode(new File("1dcode.png"));
}
/**
 * @param readImage    读取一维码图片名
 * @return void
 * */
public static void readCode(File readImage) {
    try {
        BufferedImage image = ImageIO.read(readImage);
        if (image == null) {
            return;
        }
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, "gbk");
        hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

        Result result = new MultiFormatReader().decode(bitmap, hints);
        System.out.println(result.getText());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

注意:当使用String类进行转码时,要使用Java.lang包的,Maven导包的时候会导入第三方Apache的String类

生成二维码

/** 定义二维码的宽度 */
private final static int WIDTH = 300;
/** 定义二维码的高度 */
private final static int HEIGHT = 300;
/** 定义二维码的格式 */
private final static String FORMAT = "png";

/**
 * @param file
 * @param content
 * @return void
 * */
public static void generateQRCode(File file, String content) {
    // 定义二维码参数
    Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
    // 设置编码
    hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    // 设置容错等级
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
    // 设置边距,默认为5
    hints.put(EncodeHintType.MARGIN, 2);

    try {
        BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
        Path path = file.toPath();
        // 保存到项目跟目录中
        MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    generateQRCode(new File("smt.png"), "淑玫唐家居网");
}

读取二维码

/**
 * @param file    读取二维码的文件名
 * @return void
 * */
public static void readQRCode(File file) {
    MultiFormatReader reader = new MultiFormatReader();
    try {
        BufferedImage image = ImageIO.read(file);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = reader.decode(binaryBitmap, hints);
        System.out.println("解析结果: " + new String(result.toString().getBytes("GBK"), "GBK"));
        System.out.println("二维码格式: " + result.getBarcodeFormat());
        System.out.println("二维码文本内容: " + new String(result.getText().getBytes("GBK"), "GBK"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    readQRCode(new File("smt.png"));
}

注意: Maven打印的控制台中会出现中文乱码,在IDEA Setting->maven->runner VMoptions:-Dfile.encoding=GB2312;即可解决

总结

到此这篇关于Java生成读取条形码和二维码的文章就介绍到这了,更多相关Java生成读取条形码二维码内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Java/Android 相关文章推荐
分析Netty直接内存原理及应用
Jun 14 Java/Android
HashMap实现保存两个key相同的数据
Jun 30 Java/Android
Java基础之this关键字的使用
Jun 30 Java/Android
SpringBoot 拦截器妙用你真的了解吗
Jul 01 Java/Android
Spring实现内置监听器
Jul 09 Java/Android
JavaWeb 入门:Hello Servlet
Jul 16 Java/Android
SpringBoot整合Minio文件存储
Apr 03 Java/Android
Android Flutter实现图片滑动切换效果
Apr 07 Java/Android
Java 通过手写分布式雪花SnowFlake生成ID方法详解
Apr 07 Java/Android
零基础学java之循环语句的使用
Apr 10 Java/Android
Android开发手册自定义Switch开关按钮控件
Jun 10 Java/Android
基于Android10渲染Surface的创建过程
Aug 14 Java/Android
详细了解java监听器和过滤器
Jul 09 #Java/Android
Java使用jmeter进行压力测试
java解析XML详解
使用@Value值注入及配置文件组件扫描
Jul 09 #Java/Android
详细了解MVC+proxy
Jul 09 #Java/Android
Spring实现内置监听器
Jul 09 #Java/Android
新手初学Java网络编程
Jul 07 #Java/Android
You might like
第十四节 命名空间 [14]
2006/10/09 PHP
PHP判断远程url是否有效的几种方法小结
2011/10/08 PHP
PHP 杂谈《重构-改善既有代码的设计》之一 重新组织你的函数
2012/04/09 PHP
Eclipse PHPEclipse 配置的具体步骤
2017/08/08 PHP
Javascript中的数学函数集合
2007/05/08 Javascript
40个有创意的jQuery图片和内容滑动及弹出插件收藏集之二
2011/12/31 Javascript
使用GruntJS链接与压缩多个JavaScript文件过程详解
2013/08/02 Javascript
jquery的ajax跨域请求原理和示例
2014/05/08 Javascript
深入理解JavaScript系列(45):代码复用模式(避免篇)详解
2015/03/04 Javascript
JavaScript模拟可展开、拖动与关闭的聊天窗口实例
2015/05/12 Javascript
javascript实现图片上传前台页面
2015/08/18 Javascript
如何利用JQuery实现从底部回到顶部的功能
2016/12/27 Javascript
jQuery排序插件tableSorter使用方法
2017/02/10 Javascript
第一个Vue插件从封装到发布
2017/11/22 Javascript
vue+webpack 打包文件 404 页面空白的解决方法
2018/02/28 Javascript
vue页面切换到滚动页面显示顶部的实例
2018/03/13 Javascript
微信 jssdk 签名错误invalid signature的解决方法
2019/01/14 Javascript
ES6基础之解构赋值(destructuring assignment)
2019/02/21 Javascript
JS原生瀑布流效果实现
2019/04/26 Javascript
layui扩展上传组件模拟进度条的方法
2019/09/23 Javascript
JavaScript对象属性操作实例解析
2020/02/04 Javascript
python 多线程应用介绍
2012/12/19 Python
使用Pyrex来扩展和加速Python程序的教程
2015/04/13 Python
Python cookbook(数据结构与算法)实现查找两个字典相同点的方法
2018/02/18 Python
使用pandas读取csv文件的指定列方法
2018/04/21 Python
python贪吃蛇游戏代码
2020/04/18 Python
美国正版电视节目和电影在线观看:Hulu
2018/05/24 全球购物
Carolina工作鞋官网:Carolina Footwear
2019/03/14 全球购物
Topshop美国官网:英国快速时尚品牌
2019/05/16 全球购物
一些网络技术方面的面试题
2014/05/01 面试题
Servlet方面面试题
2016/09/28 面试题
工作作风建设心得体会
2014/10/22 职场文书
大学生旷课检讨书1000字
2015/02/19 职场文书
第一军规观后感
2015/06/12 职场文书
800字作文之大雪
2019/12/04 职场文书
JMeter对MySQL数据库进行压力测试的实现步骤
2022/01/22 MySQL