Get Image Object size in Python in Bytes - BadRequest Error in Azure

Viewed 129

I have an image object that I've accepted via a streamlit interface. Here's its type: <class 'streamlit.uploaded_file_manager.UploadedFile'>

I need to get the size of this image in bytes or megabytes. The image is not stored on my device. I tried using

def img_resize(image):
    img2 = Image.open(image)
    img_file = io.BytesIO()
    img2.save(img_file, 'png')
    image_file_size = img_file.tell()
    print(image_file_size)
    img2.close()

# This function connects to azure services and generates the resources and generates the results
def azure_result(image_name, image):
    img_resize(image)

Output: 14386671 2021-08-12 12:57:01.892 Traceback (most recent call last): File "path", line 1709, in read_in_stream raise models.ComputerVisionOcrErrorException(self._deserialize, response) azure.cognitiveservices.vision.computervision.models._models_py3.ComputerVisionOcrErrorException: Operation returned an invalid status code 'Bad Request'

The file size printed is 14386671, the image size as per the system is 3.77 mb. When i further pass the image object to the Azure Cognitive Service, I get a bad request error.

How do I solve this?

1 Answers

We can get the size of an object by storing them in a variable and printing it as below:

 print(sys.getsizeof(content))

Or we can add an extension to img_file as “. size”, this will get the actual size in bytes.

enter image description here

If we would like to get the file size in KB, MB and GB and convert them to bytes we can follow below conversion table:

enter image description here

We can add these extensions in img_resize(image) functions, we’ll be able to capture the correct bytes.

Prerequisites before you connect to Azure Cognito Service is to install the pip lib as below in terminal:

pip install azure-cognitiveservices-vision-computervision

Later below code gives us insight on how to connect to Azure Cognito Service:

from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials

import os
region = os.environ['ACCOUNT_REGION']
key = os.environ['ACCOUNT_KEY']

credentials = CognitiveServicesCredentials(key)
client = ComputerVisionClient(
    endpoint="https://" + region + ".api.cognitive.microsoft.com/",
    credentials=credentials
)

Can get more information from the Python documentation for Azure.

Related