M
M
Max Payne2018-06-02 23:19:25
Python
Max Payne, 2018-06-02 23:19:25

How to convert PIL object to Bytes?

image_content = requests.get(image_url).content

image = Image.open(BytesIO(image_content))
image = image.crop((0, 0, image.size[0], image.size[0]*0.975))
image_content = BytesIO()
image.save(image_content, format='JPEG')

requests.post(url, files={'photo': ('upload.jpg', image_content)})

Why, in this case, the image is not sent to the server? I think the error is here
image_content = BytesIO()
image.save(image_content, format='JPEG')

But hard googling has turned up nothing so far.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2018-06-02
@dimonchik2013

from PIL import Image
import requests
from io import BytesIO

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

then you save, teyuya in img already has an object with data
xs what kind of manipulations with image_content = BytesIO ()
on the server is just everything
with open(filename, 'rb') as f:
        r = requests.post(url, data=f.read())

M
Maxim Vyaznikov, 2020-09-23
@ha7y

Summarizing the long correspondence in the comments to the previous answer, it turns out something like this:

image_content = requests.get(image_url).content

image = Image.open(BytesIO(image_content))
image = image.crop((0, 0, image.size[0], image.size[0]*0.975))
image_content = BytesIO()
image.seek(0)
image.save(image_content, format='JPEG')
image_content.seek(0)

requests.post(url, files={'photo': ('upload.jpg', image_content)})

Sample code on github

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question