'How to display image stored in Google Cloud bucket

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?



Solution 1:[1]

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

Solution 2:[2]

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())

Solution 3:[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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris32
Solution 2 Juho
Solution 3 bsauce