简体   繁体   English

如何从Python脚本上传Google Cloud Storage上的字节图像

[英]How to upload a bytes image on Google Cloud Storage from a Python script

I want to upload an image on Google Cloud Storage from a python script. 我想从python脚本上传Google Cloud Storage上的图像。 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 = open('img.jpg', 'r') the code works and correctly save my image on Cloud Storage. 如果gcs_image = open('img.jpg', 'r') ,代码可以正常工作并将我的图像正确保存在云存储上。 How can I directly upload a bytes image? 如何直接上传字节图像? (for example from an OpenCV/Numpy array: gcs_image = cv2.imread('img.jpg') ) (例如来自OpenCV / Numpy数组: 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

note that target_key is prefix and the name of the uploaded file. 请注意, target_key是前缀和上载文件的名称。

MediaIoBaseUpload expects an io.Base -like object and raises following error: MediaIoBaseUpload需要一个io.Base的对象,并引发以下错误:

  'numpy.ndarray' object has no attribute 'seek'

upon receiving a ndarray object. 在收到一个ndarray对象。 To solve it I am using TemporaryFile and numpy.ndarray().tofile() 要解决它我使用的是TemporaryFilenumpy.ndarray().tofile()

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient import discovery
import googleapiclient
import numpy as np
import cv2
from tempfile import TemporaryFile


scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = ServiceAccountCredentials.from_json_keyfile_name('serviceAccount.json', scopes)
service = discovery.build('storage','v1',credentials = credentials)

body = {'name':'my_image.jpg'}
with TemporaryFile() as gcs_image:
    cv2.imread('img.jpg').tofile(gcs_image)
    req = service.objects().insert(
       bucket='my_bucket’, body=body,
       media_body=googleapiclient.http.MediaIoBaseUpload(
          gcs_image, 'application/octet-stream'))

    resp = req.execute()

Be aware that googleapiclient is non-idiomatic and maintenance only (it's not developed anymore). 请注意,googleapiclient只是非惯用和维护 (它不再开发)。 I would recommend using idiomatic one . 我建议使用惯用的

In my case, I wanted to upload a PDF document to Cloud Storage from bytes. 就我而言,我想从字节上传PDF文档到云存储。

When I tried the below, it created a text file with my byte string in it. 当我尝试下面的内容时,它创建了一个带有字节字符串的文本文件。

blob.upload_from_string(bytedata)

In order to create an actual PDF file using the byte string I had to do: 为了使用我必须做的字节字符串创建一个实际的PDF文件:

blob.upload_from_string(bytedata, content_type='application/pdf')

My byte data was b64encoded, so I also had b64decode it first. 我的字节数据是b64encoded,所以我首先使用b64解码。

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

相关问题 如何从网络上传图像到Google Cloud Storage? - How to upload an image from web into Google Cloud Storage? 如何从 App Engine 将图像上传到 Google Cloud Storage - How to upload an image to Google Cloud Storage from App Engine 如何使用python将视频上传到Google云存储 - how to upload a video to google cloud storage in python 如何将文件上传到 Python 3 上的 Google Cloud Storage? - How to upload a file to Google Cloud Storage on Python 3? 将新图像文件上传到谷歌云存储或谷歌云中的文件夹时如何调用 python 脚本 - how to call a python script when a new image file is uploaded to a google cloud storage or folder in google cloud 如何使用python flask从Google云存储提供图像 - How to serve an image from google cloud storage using python flask 如何在Google Cloud Storage上运行Python脚本? - How to run Python script on Google Cloud storage? 如何使用 Python 将图像上传到谷歌云存储,而不将图像保存在我的本地磁盘上? - How to upload to google cloud storage an image using Python, without saving the image on my local disk? 如何使用AJAX将图像上传到Google云存储? - How can I upload an image using AJAX to google cloud storage? 谷歌云存储从 Python 生成器上传 - Google Cloud Storage streaming upload from Python generator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM