Azure blob UnicodeDecodeError while reading jpg using python

Viewed 396

I am reading a .jpg file in python from local directory and converting it to base64. it is working fine.

    with open(logo, 'rb') as f:
        data = f.read()
        f.close()        
    encoded = base64.b64encode(data).decode()
    
    

Now I have to read the same file from Azure blob and using below code.

    blob_container = 'operations'
    BlobPath = 'img\test.jpg'
    blob_service_client = azure_utility.get_blob_service_client()
    blob_client = blob_service_client.get_blob_client(container=blob_container, blob=BlobPath)
    data_dump = blob_client.download_blob().readall().decode()
    

getting below error.

    Exception: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

How can I read blog same jpg file like data = f.read() in blob and pass to the encoded = base64.b64encode(data).decode()

1 Answers

Try with code like this:

from azure.storage.blob import BlobClient
import base64

blob = BlobClient.from_connection_string(conn_str="your-connect-string", container_name="container_name", blob_name="blob_name")
stream = blob.download_blob()
data = stream.readall()

encoded = base64.b64encode(data).decode()
Related