Java生成读取条形码及二维码

条形码

  • 将宽度不等的多个黑条和白条,按照一定的编码规则排序,用以表达一组信息的图像标识符
  • 通常代表一串数字 / 字母,每一位有特殊含义
  • 一般数据容量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;即可解决

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值