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 相关文章推荐
Spring Data JPA使用JPQL与原生SQL进行查询的操作
Jun 15 Java/Android
浅谈什么是SpringBoot异常处理自动配置的原理
Jun 21 Java/Android
springcloud之Feign超时问题的解决
Jun 24 Java/Android
总结Java对象被序列化的两种方法
Jun 30 Java/Android
JavaWeb Servlet实现网页登录功能
Jul 04 Java/Android
Spring-cloud Config Server的3种配置方式
Sep 25 Java/Android
深入浅出讲解Java8函数式编程
Jan 18 Java/Android
SpringBoot中HttpSessionListener的简单使用方式
Mar 17 Java/Android
详解Flutter和Dart取消Future的三种方法
Apr 07 Java/Android
Java中的继承、多态以及封装
Apr 11 Java/Android
Java设计模式中的命令模式
Apr 28 Java/Android
一文了解Java动态代理的原理及实现
Jul 07 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
php 需要掌握的东西 不做浮躁的人
2009/12/28 PHP
显示youtube视频缩略图和Vimeo视频缩略图代码分享
2014/02/13 PHP
php中的curl_multi系列函数使用例子
2014/07/29 PHP
Zend Framework缓存Cache用法简单实例
2016/03/19 PHP
php实现查询功能(数据访问)
2017/05/23 PHP
关于火狐(firefox)及ie下event获取的两种方法
2012/12/27 Javascript
JQuery页面的表格数据的增加与分页的实现
2013/12/10 Javascript
js获取select标签的值且兼容IE与firefox
2013/12/30 Javascript
Javascript无参数和有参数类继承问题解决方法
2015/03/02 Javascript
JavaScript简单表格编辑功能实现方法
2015/04/16 Javascript
在Python中使用glob模块查找文件路径的方法
2015/06/17 Javascript
javascript随机抽取0-100之间不重复的10个数
2016/02/25 Javascript
jquery实现垂直和水平菜单导航栏
2020/08/27 Javascript
简单实现AngularJS轮播图效果
2020/04/10 Javascript
layer弹出层框架alert与msg详解
2017/03/14 Javascript
vuejs使用FormData实现ajax上传图片文件
2017/08/08 Javascript
微信小程序实现Session功能及无法获取session问题的解决方法
2019/05/07 Javascript
openlayers4.6.5实现距离量测和面积量测
2020/09/25 Javascript
nodejs中内置模块fs,path常见的用法说明
2020/11/07 NodeJs
[00:23]DOTA2群星共贺开放测试 25日无码时代来袭
2013/09/23 DOTA
[06:21]完美世界亚洲区首席发行官竺琦TI3采访
2013/08/26 DOTA
[03:44]2014DOTA2国际邀请赛 71专访:DK战队赛前讨论视频遭泄露
2014/07/13 DOTA
Python使用turtule画五角星的方法
2015/07/09 Python
Python中模块pymysql查询结果后如何获取字段列表
2017/06/05 Python
python将回车作为输入内容的实例
2018/06/23 Python
解决pytorch-yolov3 train 报错的问题
2020/02/18 Python
python简单实现最大似然估计&amp;scipy库的使用详解
2020/04/15 Python
MADE法国:提供原创设计师家具
2018/09/18 全球购物
美国亚马逊旗下男装网站:East Dane(支持中文)
2019/09/25 全球购物
几个Shell Script面试题
2014/04/18 面试题
艺术爱好者的自我评价分享
2013/10/08 职场文书
自我评价格式
2014/01/06 职场文书
小学毕业典礼演讲稿
2014/09/09 职场文书
自主招生学校推荐信范文
2015/03/26 职场文书
2015年财务工作总结范文
2015/03/31 职场文书
浙江省杭州市平均工资标准是多少?
2019/07/09 职场文书