4

I can successfully access the google cloud bucket from my python code running on my PC using the following code.

client = storage.Client()
bucket = client.get_bucket('bucket-name')
blob = bucket.get_blob('images/test.png')

Now I don't know how to retrieve and display image from the "blob" without writing to a file on the hard-drive?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
fisakhan
  • 704
  • 1
  • 9
  • 27
  • 1
    Whats the use case? to display the image on a webpage? – Jaboy Oct 03 '19 at 15:50
  • No. I just want to display and process the image in my python code running on my local computer. – fisakhan Oct 04 '19 at 10:07
  • Calling blob.download_as_string() returns you the blob as a string of bytes you can store in memory and work on without writing to disk. What input formats are your draw and process methods expecting? – Jaboy Oct 04 '19 at 19:18
  • The input file from bucket is .png format and I want to display/process it with pillow/opencv/matplotlib. – fisakhan Oct 07 '19 at 08:45
  • Theres a few explanations in here for pillow/opencv about how to use the in memory image https://stackoverflow.com/questions/33754935/read-a-base-64-encoded-image-from-memory-using-opencv-python-library – Jaboy Oct 08 '19 at 18:15

3 Answers3

3

You could, for example, generate a temporary url

from gcloud import storage
client = storage.Client()  # Implicit environ set-up
bucket = client.bucket('my-bucket')
blob = bucket.blob('my-blob')
url_lifetime = 3600  # Seconds in an hour
serving_url = blob.generate_signed_url(url_lifetime)

Otherwise you can set the image as public in your bucket and use the permanent link that you can find in your object details

https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME

Chris32
  • 4,716
  • 2
  • 18
  • 30
3

Download the image from GCS as bytes, wrap it in BytesIO object to make the bytes file-like, then read in as a PIL Image object.

from io import BytesIO
from PIL import Image

img = Image.open(BytesIO(blob.download_as_bytes()))

Then you can do whatever you want with img -- for example, to display it, use plt.imshow(img).

bsauce
  • 624
  • 4
  • 12
1

In Jupyter notebooks you can display the image directly with download_as_bytes:

from google.cloud import storage
from IPython.display import Image

client = storage.Client() # Implicit environment set up
# with explicit set up:
# client = storage.Client.from_service_account_json('key-file-location')

bucket = client.get_bucket('bucket-name')
blob = bucket.get_blob('images/test.png')
Image(blob.download_as_bytes())
Juho
  • 141
  • 1
  • 3
  • I get 'Blob' object has no attribute 'download_as_bytes' using your answer – antonioACR1 Jun 29 '21 at 19:42
  • This may be a problem with access rights. If the service account you are using has no permissions to the file or the file path is incorrect, blob becomes a NoneType object and cannot be downloaded. – Juho May 19 '22 at 07:27