You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Streamlit中将图片/文件上传至Deta Drive?

从NumPy ndarray上传图片到Google Drive的实现方法

核心流程

要实现从NumPy数组上传图片到Google Drive,关键是先将数组转换为标准图片格式,再通过Google Drive API完成上传操作,以下是具体步骤:


1. 安装依赖库

先确保安装所需的工具包:

pip install streamlit numpy pillow google-api-python-client oauth2client

2. 将NumPy数组转换为图片字节流

避免本地存储临时文件,直接在内存中完成格式转换:

import numpy as np
from PIL import Image
from io import BytesIO

# 假设你有一个NumPy格式的图片数组(示例为随机生成的RGB图)
img_array = np.random.randint(0, 255, (400, 400, 3), dtype=np.uint8)

# 转换为PIL Image对象
img = Image.fromarray(img_array)

# 将图片转为字节流
img_bytes = BytesIO()
img.save(img_bytes, format='PNG')  # 可根据需求选择JPG等格式
img_bytes.seek(0)  # 重置文件指针到开头

3. 初始化Google Drive服务

需要先在Google Cloud控制台创建服务账号,下载JSON格式的密钥文件(命名为credentials.json),然后完成授权:

from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
from oauth2client.service_account import ServiceAccountCredentials

# 定义API权限范围
SCOPES = ['https://www.googleapis.com/auth/drive.file']

# 加载服务账号密钥
creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', SCOPES)
drive_service = build('drive', 'v3', credentials=creds)

4. 上传字节流到Google Drive

调用Drive API完成上传,可自定义文件名、存储路径和权限:

def upload_to_drive(drive_service, img_bytes, filename):
    # 配置上传媒体
    media = MediaIoBaseUpload(img_bytes, mimetype='image/png')
    
    # 配置文件元数据
    file_metadata = {
        'name': filename,
        # 可选:指定父文件夹ID,将文件存入特定文件夹
        # 'parents': ['your-folder-id']
    }
    
    # 执行上传
    file = drive_service.files().create(
        body=file_metadata,
        media_body=media,
        fields='id'
    ).execute()
    
    print(f"文件上传成功,ID: {file.get('id')}")
    return file.get('id')

# 调用上传函数
upload_to_drive(drive_service, img_bytes, 'test_upload.png')

注意事项

  • 确保NumPy数组的dtype为uint8,否则PIL转换会出错;如果是灰度图,数组维度应为(height, width)而非(height, width, 1),可通过img_array.squeeze()去除多余维度。
  • 若需要让其他用户访问上传的文件,可在file_metadata中添加权限设置,或调用permissions().create()接口调整文件权限。
  • 服务账号需要有目标Drive文件夹的写入权限,可在Drive中共享文件夹给服务账号的邮箱。

内容的提问来源于stack exchange,提问作者NAGA VENKATA SRINIVAS MENTA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:25:33