如何从Python脚本上传Google云端存储中的字节图像 [英] How to upload a bytes image on Google Cloud Storage from a Python script
本文介绍了如何从Python脚本上传Google云端存储中的字节图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从Python脚本上传Google云端存储中的图片。这是我的代码:
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()
if gcs_image =打开('img.jpg','r')
代码正常工作,并将我的映像正确保存到云端存储上。我怎样才能直接上传一个字节图像? (例如来自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')
)
推荐答案
如果您想从文件上传图片。
If you want to upload your image from file.
import os
from google.cloud import storage
def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
full_file_path = os.path.join(local_path, local_file_name)
bucket.blob(target_key).upload_from_filename(full_file_path)
return bucket.blob(target_key).public_url
except Exception as e:
print(e)
return None
但是如果你想直接上传字节:
but if you want to upload bytes directly:
import os
from google.cloud import storage
def upload_data_to_gcs(bucket_name, data, target_key):
try:
client = storage.Client()
bucket = client.bucket(bucket_name)
bucket.blob(target_key).upload_from_string(data)
return bucket.blob(target_key).public_url
except Exception as e:
print(e)
return None
注意 target_key
是前缀和上传文件的名称。
note that target_key
is prefix and the name of the uploaded file.
这篇关于如何从Python脚本上传Google云端存储中的字节图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文