tim*_*mhj 2 pdf imagemagick python-3.x wand google-cloud-functions
尝试从本地文件系统加载 PDF 并收到“未授权”错误。
“文件“/env/local/lib/python3.7/site-packages/wand/image.py”,第 4896 行,在读取 self.raise_exception() 文件“/env/local/lib/python3.7/site- package/wand/resource.py", line 222, in raise_exception raise e wand.exceptions.PolicyError: 未授权`/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.
Run Code Online (Sandbox Code Playgroud)
ImageMagick 应该被授权访问本地文件系统上的文件,因此它应该加载文件而不是这个“未授权”错误。
由于Ghostscript 存在安全漏洞,ImageMagick 的 PDF 阅读已被禁用。问题是设计使然,ImageMagick 团队的安全缓解措施将一直存在。ImageMagick 再次启用对 PDF 的 Ghostscript 处理,Google Cloud Functions 更新到新版本的 ImageMagick,再次启用 PDF 处理。
我找不到 GCF 中 ImageMagick/Wand 问题的修复程序,但作为在 Google Cloud Functions 中将 PDF 转换为图像的解决方法,您可以使用此 [ghostscript 包装器][2] 直接请求将 PDF 转换为图像Ghostscript 并绕过 ImageMagick/Wand。然后,您可以毫无问题地将 PNG 加载到 ImageMagick 或 OpenCV 中。
要求.txt
google-cloud-storage
ghostscript==0.6
Run Code Online (Sandbox Code Playgroud)
主文件
# 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)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助面临同样问题的人。
归档时间: |
|
查看次数: |
920 次 |
最近记录: |