Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. How can I directly upload a bytes image? (for example from an OpenCV/Numpy array: gcs_image = cv2.imread('img.jpg'))

like image 416
Davide Biraghi Avatar asked Sep 06 '17 14:09

Davide Biraghi


People also ask

How do I upload data to Google Cloud Storage?

In the Google Cloud console, go to the Cloud Storage Buckets page. In the list of buckets, click on the name of the bucket that you want to upload an object to. In the Objects tab for the bucket, either: Drag and drop the desired files from your desktop or file manager to the main pane in the console.


1 Answers

In my case, I wanted to upload a PDF document to Cloud Storage from bytes.

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:

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

My byte data was b64encoded, so I also had b64decode it first.

like image 156
Melissa Guo Avatar answered Sep 18 '22 11:09

Melissa Guo