繁体   English   中英

将图像上传到 Google Cloud 而不是保存到磁盘 (Python)

[英]Upload images to Google Cloud instead of saving to disk (Python)

我有一个脚本,它从网络下载某些图像(<1 MB)并保存到本地磁盘。 我可以将它保存到 Google Cloud Storage 存储分区而不是本地系统吗?

def downloadImage(url):
    try:
        print("Downloading {}".format(url))
        image_name = str(url).split('/')[-1]
        resp = urlopen(url)
        image = np.asarray(bytearray(resp.read()), dtype="uint8")
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)
        cv2.imwrite(current_path + "\\Downloaded\\" + image_name, image)
    except Exception as error:
        print(error)

您可以使用GCS Python 客户端库以编程方式执行与 GCS 相关的任务。 以下代码会将位于/PATH/TO/SOURCE_FILE的本地文件上传到 GCS 存储桶gs://BUCKET_NAME

from google.cloud import storage

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket"""

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print(
        "File {} uploaded to {}.".format(
            source_file_name, destination_blob_name
        )
    )


BUCKET_NAME = "BUCKET_NAME"
SOURCE_FILE_NAME = "/PATH/TO/SOURCE_FILE"
DESTINATION_FILE_NAME = "DESTINATION_FILE"

upload_blob(BUCKET_NAME, SOURCE_FILE_NAME, DESTINATION_FILE_NAME)

请记住,为了使用upload_blob方法,必须安装 GCS Python 客户端库并设置身份验证凭据。 您可以在此处找到有关如何实施这些步骤的信息。

试试这个: https : //cloud.google.com/python

请记住,始终检查是否有您想要的库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM