How to upload a bytes image on Google Cloud Storage from a Python script(如何通过 Python 脚本在 Google Cloud Storage 上上传字节图像)
问题描述
我想通过 python 脚本将图像上传到 Google Cloud Storage.这是我的代码:
I want to upload an image on Google Cloud Storage from a python script. This is my code:
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scop
es)
service = discovery.build('storage','v1',credentials = credentials)
body = {'name':'my_image.jpg'}
req = service.objects().insert(
bucket='my_bucket', body=body,
media_body=googleapiclient.http.MediaIoBaseUpload(
gcs_image, 'application/octet-stream'))
resp = req.execute()
如果 gcs_image = open('img.jpg', 'r') 代码可以正常工作并将我的图像正确保存在 Cloud Storage 上.如何直接上传字节图像?(例如来自 OpenCV/Numpy 数组:gcs_image = cv2.imread('img.jpg'))
if gcs_image = open('img.jpg', 'r') the code works and correctly save my image on Cloud Storage. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: gcs_image = cv2.imread('img.jpg'))
推荐答案
就我而言,我想将 PDF 文档从字节上传到云存储.
In my case, I wanted to upload a PDF document to Cloud Storage from bytes.
当我尝试以下操作时,它创建了一个包含我的字节字符串的文本文件.
When I tried the below, it created a text file with my byte string in it.
blob.upload_from_string(bytedata)
为了使用字节字符串创建一个实际的 PDF 文件,我必须这样做:
In order to create an actual PDF file using the byte string I had to do:
blob.upload_from_string(bytedata, content_type='application/pdf')
我的字节数据是b64encoded,所以我也先b64decode.
My byte data was b64encoded, so I also had b64decode it first.
这篇关于如何通过 Python 脚本在 Google Cloud Storage 上上传字节图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过 Python 脚本在 Google Cloud Storage 上上传字节图像
基础教程推荐
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
