【问题标题】:Can't load PDF with Wand/ImageMagick in Google Cloud Function无法在 Google Cloud 功能中使用 Wand/ImageMagick 加载 PDF
【发布时间】:2019-08-24 08:26:19
【问题描述】:

尝试从本地文件系统加载 PDF 并收到“未授权”错误。

“文件”/env/local/lib/python3.7/site-packages/wand/image.py”,第 4896 行,在读取 self.raise_exception() 文件“/env/local/lib/python3.7 /site-packages/wand/resource.py",第 222 行,在 raise_exception 中引发 e wand.exceptions.PolicyError: not authorized `/tmp/tmp_iq12nws' @error/constitute.c/ReadImage/412

PDF 文件已从 GCS 成功保存到本地“服务器”,但不会被 Wand 加载。将图像加载到 OpenCV 中不是问题,只是在尝试使用 Wand/ImageMagick 加载 PDF 时发生

将 PDF 从 GCS 加载到本地文件系统到 Wand/ImageMagick 的代码如下

_, temp_local_filename = tempfile.mkstemp()
gcs_blob = STORAGE_CLIENT.bucket('XXXX').get_blob(results["storedLocation"])
gcs_blob.download_to_filename(temp_local_filename)
# load the pdf into a set of images using imagemagick
with(Image(filename=temp_local_filename, resolution=200)) as source:
    #run through pages and save images etc.

ImageMagick 应该被授权访问本地文件系统上的文件,因此它应该毫无问题地加载文件,而不是出现“未授权”错误。

【问题讨论】:

标签: python-3.x pdf imagemagick google-cloud-functions wand


【解决方案1】:

由于安全漏洞Ghostscript had,ImageMagick 的 PDF 阅读功能已被禁用。这个问题是设计使然,ImageMagick 团队的安全缓解措施将一直存在。 ImageMagick 再次启用对 PDF 的 Ghostscript 处理,Google Cloud Functions 更新到新版本的 ImageMagick,并再次启用 PDF 处理。

我找不到 GCF 中的 ImageMagick/Wand 问题的修复方法,但作为将 PDF 转换为 Google Cloud Functions 中的图像的解决方法,您可以使用此 [ghostscript wrapper][2] 直接请求将 PDF 转换为通过 Ghostscript 生成图像并绕过 ImageMagick/Wand。然后,您可以毫无问题地将 PNG 加载到 ImageMagick 或 OpenCV 中。

requirements.txt

google-cloud-storage
ghostscript==0.6

ma​​in.py

    # create a temp filename and save a local copy of pdf from GCS
    _, temp_local_filename = tempfile.mkstemp()
    gcs_blob = STORAGE_CLIENT.bucket('XXXX').get_blob(results["storedLocation"])
    gcs_blob.download_to_filename(temp_local_filename)
    # create a temp folder based on temp_local_filename
    temp_local_dir = tempfile.mkdtemp()
    # use ghostscript to export the pdf into pages as pngs in the temp dir
    args = [
        "pdf2png", # actual value doesn't matter
        "-dSAFER",
        "-sDEVICE=pngalpha",
        "-o", temp_local_dir+"page-%03d.png",
        "-r300", temp_local_filename
        ]
    # the above arguments have to be bytes, encode them
    encoding = locale.getpreferredencoding()
    args = [a.encode(encoding) for a in args]
    #run the request through ghostscript
    ghostscript.Ghostscript(*args)
    # read the files in the tmp dir and process the pngs individually
    for png_file_loc in glob.glob(temp_local_dir+"*.png"):
        # loop through the saved PNGs, load into OpenCV and do what you want
        cv_image = cv2.imread(png_file_loc, cv2.IMREAD_UNCHANGED)

希望这对面临同样问题的人有所帮助。

【讨论】:

    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 2021-12-14
    • 2021-11-09
    • 2016-12-03
    • 2014-07-05
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多