如何提供 Google Cloud Storage 图片?

在Python中,你可以使用`google-cloud-storage`库来上传和下载图片到Google Cloud Storage。以下是一个简单的示例,展示了如何上传图片到存储桶,并获取一个带有签名URL的链接以供下载。

首先,你需要安装`google-cloud-storage`库:

```bash
pip install google-cloud-storage
```

然后,你可以使用以下代码来上传和下载图片:

```python
from google.cloud import storage
import os

# 初始化Google Cloud Storage客户端
storage_client = storage.Client()

# 指定存储桶名称和要上传的图片文件路径
bucket_name = 'your-bucket-name'
source_file_name = '/path/to/your/image.jpg'
destination_blob_name = 'folder/in/bucket/image.jpg'

# 上传图片到存储桶
def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    blob = storage_client.bucket(bucket_name).blob(destination_blob_name)

    # 上传文件内容到Blob
    with open(source_file_name, "rb") as source_file:
        blob.upload_from_file(source_file)

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

# 下载图片从存储桶
def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    blob = storage_client.bucket(bucket_name).blob(source_blob_name)

    # 从Blob下载文件内容到指定路径
    with open(destination_file_name, "wb") as destination_file:
        blob.download_to_file(destination_file)

    print(f"Blob {source_blob_name} downloaded to {destination_file_name}.")

# 上传图片
upload_blob(bucket_name, source_file_name, destination_blob_name)

# 获取带有签名URL的链接以供下载
def generate_signed_url(bucket_name, blob_name, expiration=3600):
    """Generates a signed URL for accessing the specified blob.

    Args:
        bucket_name (str): The Google Cloud Storage bucket name.
        blob_name (str): The blob name.

    Returns:
        str: The signed URL.
    """
    client = storage.Client()
    bucket = client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)

    # 生成带有签名URL的链接
    url = blob.generate_signed_url(version="v4", expiration=expiration)

    return url

# 获取并打印签名URL
signed_url = generate_signed_url(bucket_name, destination_blob_name)
print(f"Signed URL: {signed_url}")

# 如果需要下载图片,可以使用以下代码:
# download_blob(bucket_name, destination_blob_name, '/path/to/download/image.jpg')
```

注意:在实际应用中,你需要替换`your-bucket-name`和`/path/to/your/image.jpg`等变量为你的实际存储桶名称和图片文件路径。同时,你也可以根据需要调整签名URL的过期时间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潮易

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值