1

A customer sends a multipart file to me, I read it with:

    blob = request.files['file'].read()

I have a blob file in hand. Now I have to send this file with requests like open('file.png', 'rb'). How can I convert blob to something like rb mode. With open I could not open blob directly.

The below code did not work:

opened_file = open(request.files['file'], 'rb')

And I got the following error:

TypeError: coercing to Unicode: need string or buffer, FileStorage found

Is there a way to do that without saving it on file system? I send my requests to somewhere else:

files = dict({'file': byteArrayFile})
r = requests.post(self.url, files=files, headers=headers)

3 Answers 3

1

request.files['file'] is already a file-like object (it's a FileStorage instance), so you can use that directly; you don't need to open it.

r = requests.post(self.url, files={"file": request.files["file"]}, headers=headers)

You can think of a file-like object as an open file. They behave the same way.

Sign up to request clarification or add additional context in comments.

Comments

1

try using

from PIL import Image
import requests
from io import BytesIO

response = requests.get(url)
img = Image.open(BytesIO(response.content))

it worked for me and for testing if you wish to have a look on the images try

img.show()

Comments

0

If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.

In my case, I needed my images where stored in a blob column in a db table:

def select_all_X_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT ImageData from PiecesTable")    
    rows = cur.fetchall()    
    return rows

I then created a helper function to change my dataset into np.array:

X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))

def convertToByteIO(imagesArray):
    """
    # Converts an array of images into an array of Bytes
    """
    imagesList = []

    for i in range(len(imagesArray)):  
        img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
        imagesList.insert(i, np.array(img))

    return imagesList

After this, I was able to use the byteArrays in my Neural Network.

plt.imshow(imagesList[0])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.