【问题标题】:How write extracted image to file object instead of to file system?如何将提取的图像写入文件对象而不是文件系统?
【发布时间】:2014-12-15 09:38:24
【问题描述】:

我正在使用 Python pdfminer library 从 PDF 中提取文本和图像。由于TextConverter class 默认写入sys.stdout,因此我使用StringIO 将文本作为变量捕获,如下所示(参见粘贴:

def extractTextAndImagesFromPDF(rawFile):
    laparams = LAParams()
    imagewriter = ImageWriter('extractedImageFolder/')    
    resourceManager = PDFResourceManager(caching=True)

    outfp = StringIO()  # Use StringIO to catch the output later.
    device = TextConverter(resourceManager, outfp, codec='utf-8', laparams=laparams, imagewriter=imagewriter)
    interpreter = PDFPageInterpreter(resourceManager, device)
    for page in PDFPage.get_pages(rawFile, set(), maxpages=0, caching=True, check_extractable=True):
        interpreter.process_page(page)
    device.close()    
    extractedText = outfp.getvalue()  # Get the text from the StringIO
    outfp.close()
    return extractedText 

这适用于提取的文本。此功能还可以提取 PDF 中的图像并将它们写入'extractedImageFolder/'。这也可以,但我现在希望将图像“写入”文件对象而不是文件系统,以便我可以对它们进行一些后期处理。

ImageWriter class 定义一个文件 (fp = file(path, 'wb')),然后写入该文件。我想要的是我的extractTextAndImagesFromPDF() 函数也可以返回文件对象列表,而不是直接将它们写入文件。我想我还需要为此使用StringIO,但我不知道该怎么做。部分还因为写入文件是在 pdfminer 中进行的。

有人知道如何返回文件对象列表而不是将图像写入文件系统吗?欢迎所有提示!

【问题讨论】:

    标签: python pdf io stream pdfminer


    【解决方案1】:

    这是一个 hack,允许您提供自己的文件指针来写入:

       # add option in aguments to supply your own file pointer
       def export_image(self, image, fp=None):
            ...
            # change this line:
            # fp = file(path, 'wb')
            # add instead:
            fp = fp if fp else file(path, 'wb')
            ...
            # and this line:
            # return name
            # add instead:
            return (fp, name,) if fp else name
    

    现在你需要使用:

    # create file-like object backed by string buffer
    fp = stringIO.stringIO()
    image_fp, name = export_image(image, fp)
    

    并且您的图像应该存储在fp

    请注意,export_image 的行为(如果在其他地方使用)保持不变。

    【讨论】:

    • 谢谢!不过有2个问题。首先:我需要分叉 pdfminer 库,我希望在不分叉的情况下这样做。第二;如果我决定分叉 pdfminer,export_image() 可以返回 fp,但 export_image() 仅在 receive_layout() (github.com/euske/pdfminer/blob/master/pdfminer/…) 中调用,而 end_page() (github.com/euske/pdfminer/blob/master/pdfminer/converter.py#L50) 又在其中调用turn 在process_page() (github.com/euske/pdfminer/blob/master/pdfminer/…) 中调用。
    • 这让它变得相当复杂。所以我的后续问题;您知道如何在不分叉 pdfminer 的情况下返回文件吗?如果没有,您是否有任何指示我如何轻松获取图像列表而无需编辑无数行代码?
    • 您的问题是 pdfminer 在他身边创建文件。如果您无权以您想要的方式获取数据 - 您可以保存到文件并稍后加载该数据,或者更改 API(fork)。我会想出一个hack(这永远只是一个hack),如果我想出一些东西,我会告诉你...
    猜你喜欢
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    相关资源
    最近更新 更多