PDF二维码识别,PDF转图片再识别二维码java实现

识别PDF中二维码

实现步骤:

1.使用icepdf把pdf转化为图片

2.使用google的zxing识别图片中的二维码

包引用

gradle 复制代码
    // https://central.sonatype.com/artifact/com.google.zxing/core
    implementation 'com.google.zxing:core:3.5.3'
    
    // https://central.sonatype.com/artifact/com.google.zxing/javase
    implementation 'com.google.zxing:javase:3.5.3'
    
    // https://central.sonatype.com/artifact/org.icepdf.os/icepdf-core
    implementation('org.icepdf.os:icepdf-core:6.2.2') {
        exclude group: 'javax.media', module: 'jai_core'
    }

代码部分,一个类几个方法就实现了,还是比较简单

java 复制代码
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

public class Test {
    //缩放比例
    public static float scale = 2f;
    //旋转角度
    public static float rotation = 0f;

    //识别PDF中的二维码
    public static void main(String[] args) throws Exception {
        long time = System.currentTimeMillis();
        File file = new File("C:\\Users\\yujing\\Desktop\\111.pdf");
        //PDF转byte
        byte[] pdfBytes = fileToByte(file);
        //byte转imageByte
        byte[] imageBytes = pdfByteToImgByte(pdfBytes);
        //保存到本地
        //byteToFile(imageBytes, new File("D:/pdf_" + UUID.randomUUID() + ".png"));
        //二维码识别
        String text = imageToQRCode(imageBytes);
        System.out.println(text);
        System.out.println("耗时:" + (System.currentTimeMillis() - time) + "ms");
    }

    /**
     * pdf转图片
     */
    public static byte[] pdfByteToImgByte(byte[] pdfBytes) throws Exception {
        byte[] result = null;
        Document document = new Document();
        document.setByteArray(pdfBytes, 0, pdfBytes.length, "");
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", bos);
                result = bos.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
            }
            image.flush();
        }
        document.dispose();
        return result;
    }

    /**
     * 识别 png图片中的二维码信息
     */
    public static String imageToQRCode(byte[] imageInByte) throws Exception {
        MultiFormatReader multiFormatReader = new MultiFormatReader();
        InputStream in = new ByteArrayInputStream(imageInByte);
        BufferedImage image = ImageIO.read(in);
        // 定义二维码参数
        Map<DecodeHintType, String> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
        // 获取读取二维码结果
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        Result result = multiFormatReader.decode(binaryBitmap, hints);
        return result.getText();
    }

    public static byte[] fileToByte(File file) {
        if (file == null || !file.exists()) return null;
        try (FileInputStream stream = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream((int) file.length())) {
            byte[] b = new byte[1024 * 4];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            return out.toByteArray();
        } catch (IOException ignored) {
        }
        return null;
    }

    public static boolean byteToFile(byte[] bytes, File file) {
        if (!Objects.requireNonNull(file.getParentFile()).exists()) // 如果位置不存在
            file.getParentFile().mkdirs();
        if (file.exists()) file.delete();
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            out.write(bytes);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            System.out.println("No Find File");
            return false;
        } catch (IOException e) {
            System.out.println("IO Error");
            return false;
        }
        return true;
    }
}
相关推荐
邓不利东1 小时前
Spring中过滤器和拦截器的区别及具体实现
java·后端·spring
witton1 小时前
Go语言网络游戏服务器模块化编程
服务器·开发语言·游戏·golang·origin·模块化·耦合
草履虫建模2 小时前
Redis:高性能内存数据库与缓存利器
java·数据库·spring boot·redis·分布式·mysql·缓存
苹果醋32 小时前
Vue3组合式API应用:状态共享与逻辑复用最佳实践
java·运维·spring boot·mysql·nginx
枯萎穿心攻击2 小时前
ECS由浅入深第三节:进阶?System 的行为与复杂交互模式
开发语言·unity·c#·游戏引擎
Jerry Lau2 小时前
go go go 出发咯 - go web开发入门系列(一) helloworld
开发语言·前端·golang
nananaij2 小时前
【Python基础入门 re模块实现正则表达式操作】
开发语言·python·正则表达式
Micro麦可乐2 小时前
Java常用加密算法详解与实战代码 - 附可直接运行的测试示例
java·开发语言·加密算法·aes加解密·rsa加解密·hash算法
掉鱼的猫2 小时前
Java MCP 鉴权设计与实现指南
java·openai·mcp
天下一般2 小时前
go入门 - day1 - 环境搭建
开发语言·后端·golang