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

识别PDF中二维码

实现步骤:
1.使用icepdf把pdf转化为图片
2.使用google的zxing识别图片中的二维码

包引用

    // 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'
    }

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

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;
    }
}
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Python 的 `pdfminer` 库来提取 PDF 文件中的文本,然后使用 `pyzbar` 库来识别二维码。以下是一个示例代码: ```python import io import pdfminer import pyzbar.pyzbar as pyzbar from PIL import Image # 从 PDF 文件中提取文本 def extract_text_from_pdf(pdf_file): output = io.StringIO() with open(pdf_file, 'rb') as f: parser = pdfminer.pdfparser.PDFParser(f) doc = pdfminer.pdfdocument.PDFDocument(parser) for page in pdfminer.pdfinterp.PDFPageInterpreter(pdfminer.pdfinterp.PDFResourceManager(), pdfminer.pdfinterp.PDFPageInterpreter): page_resource_manager = pdfminer.pdfinterp.PDFResourceManager() device = pdfminer.pdfdevice.TagExtractor(page_resource_manager, outfp=output, laparams=None) interpreter = pdfminer.pdfinterp.PDFPageInterpreter(page_resource_manager, device) interpreter.process_page(page) return output.getvalue() # 在图像中查找二维码 def find_qr_codes(image_file): img = Image.open(image_file) codes = pyzbar.decode(img) return [code.data.decode('utf-8') for code in codes if code.type == 'QRCODE'] # 从 PDF 文件中查找二维码 def find_qr_codes_in_pdf(pdf_file): text = extract_text_from_pdf(pdf_file) codes = [] for line in text.split('\n'): codes += find_qr_codes(line.strip()) return codes # 示例用法 pdf_file = 'example.pdf' codes = find_qr_codes_in_pdf(pdf_file) print(codes) ``` 这个示例代码假设 PDF 文件中的每行文本都是一个二维码。它首先使用 `pdfminer` 库提取 PDF 文件中的文本,然后使用 `pyzbar` 库在其中查找二维码。对于每个找到的二维码,它将其解码并将其作为字符串添加到结果列表中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值