python - 将枕头图像从 PDF 保存到 Google 云服务器
问题描述
我正在开发一个 Django Web 应用程序,它接收 PDF 文件并对 PDF 的每一页执行一些图像处理。我收到了一份 PDF,我需要将每一页保存到我的 Google Cloud Storage 中。我正在使用pdf2image
'sconvert_from_path()
为 PDF 中的每一页生成枕头图像列表。现在,我想将这些图像保存到谷歌云存储,但我想不通。
我已成功将这些枕头图像保存在本地,但我不知道如何在云中执行此操作。
fullURL = file.pdf.url
client = storage.Client()
bucket = client.get_bucket('name-of-my-bucket')
blob = bucket.blob(file.pdf.name[:-4] + '/')
blob.upload_from_string('', content_type='application/x-www-form-urlencoded;charset=UTF-8')
pages = convert_from_path(fullURL, 400)
for i,page in enumerate(pages):
blob = bucket.blob(file.pdf.name[:-4] + '/' + str(i) + '.jpg')
blob.upload_from_string('', content_type='image/jpeg')
outfile = file.pdf.name[:-4] + '/' + str(i) + '.jpg'
page.save(outfile)
of = open(outfile, 'rb')
blob.upload_from_file(of)
解决方案
由于您已将文件保存在本地,因此它们可以在运行 Web 应用程序的本地目录中使用。
您可以做的只是遍历该目录的文件并将它们一一上传到谷歌云存储。
这是一个示例代码:
您将需要这个库:
谷歌云存储
Python代码:
#Libraries
import os
from google.cloud import storage
#Public variable declarations:
bucket_name = "[BUCKET_NAME]"
local_directory = "local/directory/of/the/files/for/uploading/"
bucket_directory = "uploaded/files/" #Where the files will be uploaded in the bucket
#Upload file from source to destination
def upload_blob(source_file_name, destination_blob_name):
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
#Iterate through all files in that directory and upload one by one using the same filename
def upload_files():
for filename in os.listdir(local_directory):
upload_blob(local_directory + filename, bucket_directory + filename)
return "File uploaded!"
#Call this function in your code:
upload_files()
注意:我已经在 Google App Engine 网络应用程序中测试了代码,它对我有用。了解它的工作原理并根据您的需要进行修改。我希望这会有所帮助。
推荐阅读
- javascript - 事件侦听器如何使用 setInterval?
- flutter - 在通道风味上找不到方法 get Flavor 的实现
- php - 如何将 post_content 移动到 wp_postmeta
- c++ - `char **argv` 和 `char** argv` 有什么区别?
- reactjs - findDOMNode 在 StrictMode 中已弃用。findDOMNode 被传递了一个在 StrictMode Material UI 中的 Transition 实例
- javascript - 离线时发生 Firestore 更改时,NGRX 状态未更新
- shell - 从终端发送和读取串行命令
- python - 多处理中的多线程有意义吗?
- r - R Shiny:使用 Leaflet Map Click 更新多个相关的下拉菜单
- java - 当我尝试模拟一个休息模板时,为什么 mockito 告诉我方法 thenReturn 不适用于参数?